<?php


namespace Home\Controller;


class LiveController extends HomeController {
    /****************公共接口部分********************/
    /**
     * 职业列表
     * */
    public function job_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $list = M('job')->select();
            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'获取数据失败',[]);
            }
        }
    }
    public function look_zb_status(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if (empty($uid)) return api_return(2,'请传入用户id');

            $number = M('user')->where(['id' => $uid])->getField('number');

            $res = singer_channel($number);
            if($res){
                return api_return(1,'查询状态成功',$res);
            }else{
                return api_return(1,'查询状态失败',[]);
            }

        }
    }

    /**
     * 短信发送
     * */
    public function send_sms(){
        if (IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $mobile = $input['mobile'];
            $key = $input['key'];
            $type = $input['type'];//1：注册；2：重置密码

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            //获取手机号
            $pattern = "/^1[34578]\d{9}$/";
            if (empty($mobile)) {
                return api_return(2,'请输入手机号');
            } else {
                if (preg_match($pattern, $mobile)) {
                    //判断当前手机有没有发送过验证码

                    if($type == 1){
                        $count = M('user')->where(['mobile' => $mobile])->count();
                        if($count > 0) return api_return(2,'该手机号码已被注册');
                    }

                    $time_map['create_time'] = ['gt',time()-60*60];//过去一个小时
                    $send_count = M('sms_code')->where(array('mobile'=>$mobile))->where($time_map)->count();
                    if($send_count >= 3) return api_return(2,'一小时之内只能发送3次验证码');

                    $result = M('sms_code')->where(array('mobile'=>$mobile))->order('create_time desc')->find();
                    $result = time()-$result['create_time'];
                    if ($result < 60 && $result>0) {
                        return api_return(2,'当前手机号操作频繁,请稍60秒后发送');
                    }
                    $authnum = rand(100000,999999);
                    $statusStr = array(
                        "0" => 1,
                        "-1" => "参数不全",
                        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                        "30" => "密码错误2",
                        "40" => "账号不存在",
                        "41" => "余额不足",
                        "42" => "帐户已过期",
                        "43" => "IP地址限制",
                        "50" => "内容含有敏感词"
                    );
                    $smsapi = "http://api.smsbao.com/";
                    $user = C('WEB_SMS_ACC'); //短信平台帐号
                    $pass = md5(C('WEB_SMS_PWD')); //短信平台密码
                    $content = "【直播平台】尊敬的用户您的验证码" . $authnum . "如非本人操作，请忽略。";//要发送的短信内容
                    $phone = $mobile;//要发送短信的手机号码
                    $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
                    $result = file_get_contents($sendurl);
                    if ($result == 0) {
                        $info['code'] = $authnum;
                        $info['mobile'] = $phone;
                        $info['create_time'] = time();
                        $info['failure_time'] = time()+600;//失效时间：10分钟
                        M('sms_code')->add($info);
                        return api_return(1,'短信发送成功',$authnum);
                    } else {
                        return api_return(2,$statusStr[$result]);
                    }
                } else {
                    return api_return(2,'手机号码格式错误');
                }
            }
        }
    }

    /**
     * 手机号注册
     * */
    public function mobile_register(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $mobile = $input['mobile'];
            $password = $input['password'];
            $nickname = $input['nickname'];
            $code = $input['code'];

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if (empty($mobile)) return api_return(2,'请传入手机号');
            if (empty($nickname)) return api_return(2,'请传入昵称');
            if (empty($password)) return api_return(2,'请传入密码');
            if (empty($code)) return api_return(2,'请传入验证码');

            $count = M('user')->where(['mobile' => $mobile])->count();
            if($count > 0) return api_return(2,'该手机号已被注册');

            $sms = M('sms_code')->where(['mobile' => $mobile])->order('create_time desc')->limit(1)->find();
            if (!$sms) return api_return(2,'该手机号码未发送验证码');

            if ($sms['failure_time'] < time()) return api_return(2,'验证码已失效');
            if ($code != $sms['code']) return api_return(2,'验证码错误');

            $data = [
                'mobile' => $mobile,
                'nickname' => $nickname,
                'password' => md5($password)
            ];

            $res = M('user')->add($data);

            if($res){
                $number = rand_num($res,7);
                M('user')->where(['id' => $res])->setField('number', $number);

                $number = M('user')->where(['id' => $res])->getField('number');

                return api_return(1,'注册成功',$number);
            }else{
                return api_return(2,'注册失败');
            }
        }
    }

    /**
     * 绑定手机号
     * */
    public function bind_mobile(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $mobile = $input['mobile'];
            $code = $input['code'];

            $bind_exp = C('BIND_EXP');//绑定手机号所获取的经验值

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if (empty($uid)) return api_return(2,'请传入用户id');
            if (empty($mobile)) return api_return(2,'请传入手机号');
            if (empty($code)) return api_return(2,'请传入验证码');

            $count = M('user')->where(['mobile' => $mobile])->count();
            if($count > 0) return api_return(2,'该手机号已被使用');

            $sms = M('sms_code')->where(['mobile' => $mobile])->order('create_time desc')->limit(1)->find();
            if (!$sms) return api_return(2,'该手机号码未发送验证码');

            if ($sms['failure_time'] < time()) return api_return(2,'验证码已失效');
            if ($code != $sms['code']) return api_return(2,'验证码错误');

            $is_bind = M('user')->where(['id' => $uid])->getField('mobile');

            if($is_bind == '') M('user')->where(['id' => $uid])->setInc('exp',$bind_exp);

            $res = M('user')->where(['id' => $uid])->save(['mobile' => $mobile]);

            if($res){
                return api_return(1,'绑定手机号成功');
            }else{
                return api_return(2,'绑定手机号失败');
            }

        }
    }

    /**
     * 第三方登录
     * */
    public function third_login(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $nickname = $input['nickname'];
            $qqnum = $input['qqnum']?$input['qqnum']:'';
            $sex = $input['sex'];
            $avatar_img = $input['avatar_img'];
            $openid = $input['openid'];
            $type = $input['type'];//1：微信登录；2：QQ登录

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($type)) return api_return(2,'请传入type');
            if($type == 2 && empty($qqnum)) return api_return(2,'请传入QQ号');
            if(empty($nickname)) return api_return(2,'请传入昵称');
            if(empty($sex)) return api_return(2,'请传入性别');
            if(empty($avatar_img)) return api_return(2,'请传入用户头像地址');
            if(empty($openid)) return api_return(2,'请传入openid');

            $count = M('user')->where(['openid' => $openid])->count();
            if($count){
                $res = M('user')->where(['openid' => $openid])->getField('id');
            }else{
                //第一次登陆，数据入库
                $data = [
                    'nickname' => $nickname,
                    'sex' => $sex,
                    'avatar_img' => $avatar_img,
                    'openid' => $openid,
                ];
                if($type == 2) $data['qqnum'] = $qqnum;

                $res = M('user')->add($data);
                M('user')->where(['id' => $res])->setField('number', rand_num($res,10));
            }
            if($res){
                $info = M('user')->field('is_anchor,number')->where(['id' => $res])->find();
                $info['uid'] = $res;

                return api_return(1,'登录成功',$info);
            }else{
                return api_return(2,'登录失败');
            }
        }
    }

    /**
     * 手机号登录
     * */
    public function mobile_login(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $mobile = $input['mobile'];
            $password = $input['password'];

            if ($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($mobile)) return api_return(2,'请输入账号');
            if(empty($password)) return api_return(2,'请输入密码');

            $count = M('user')->where(['mobile' => $mobile])->count();

            if($count > 0){
                $where = [
                    'mobile' => $mobile,
                    'password' => md5($password)
                ];

                $uid = M('user')->where($where)->getField('id');
                if($uid){
                    $info = M('user')->field('is_anchor,number,nickname')->where(['id' => $uid])->find();
                    $info['uid'] = $uid;
                    $info['password'] = $password;
                    $userSig = get_UserSig($info['number']);

                    $token = "" . rand();
                    $refreshToken = "" . rand();
                    $roomservicesign = array("sdkAppID" => C('YUN_SDKAPPID'), "accountType" => C('ACCOUNT_TYPE'), "userID" => $info['number'], "userSig" => $userSig);

                    $cosinfo = array('Bucket' => C('BUCKET'), 'Region' => C('REGION'), 'Appid' => C('ZB_APPID'), 'SecretId' => C('SECRET_ID'));

                    $info['xzb_data'] = array('token' => $token, 'refresh_token' => $refreshToken, 'expires' => 24*60*60*180, 'roomservice_sign' => $roomservicesign, 'cos_info' => $cosinfo);

                    return api_return(1,'登录成功',$info);
                }else{
                    $token = "" . rand();
                    $refreshToken = "" . rand();
                    $roomservicesign = array("sdkAppID" => C('YUN_SDKAPPID'), "accountType" => C('ACCOUNT_TYPE'), "userID" => '', "userSig" => '');

                    $cosinfo = array('Bucket' => C('BUCKET'), 'Region' => C('REGION'), 'Appid' => C('ZB_APPID'), 'SecretId' => C('SECRET_ID'));

                    $info['xzb_data'] = array('token' => $token, 'refresh_token' => $refreshToken, 'expires' => 24*60*60*180, 'roomservice_sign' => $roomservicesign, 'cos_info' => $cosinfo);

                    return api_return(2,'密码错误',$info);
                }
            }else{
                $token = "" . rand();
                $refreshToken = "" . rand();
                $roomservicesign = array("sdkAppID" => C('YUN_SDKAPPID'), "accountType" => C('ACCOUNT_TYPE'), "userID" => '', "userSig" => '');

                $cosinfo = array('Bucket' => C('BUCKET'), 'Region' => C('REGION'), 'Appid' => C('ZB_APPID'), 'SecretId' => C('SECRET_ID'));

                $info['xzb_data'] = array('token' => $token, 'refresh_token' => $refreshToken, 'expires' => 24*60*60, 'roomservice_sign' => $roomservicesign, 'cos_info' => $cosinfo);

                return api_return(2,'账号不存在',$info);
            }
        }
    }

    /**
     * 修改密码
     * */
    public function edit_pwd(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $password = $input['password'];
            $new_password = $input['new_password'];

            $mobile = M('user')->where(['id' => $uid])->getField('mobile');

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($mobile)) return api_return(2,'请输入账号');
            if(empty($password)) return api_return(2,'请输入密码');
            if(empty($new_password)) return api_return(2,'请输入新密码');

            $count = M('user')->where(['mobile' => $mobile])->count();

            if($count){
                $where = [
                    'mobile' => $mobile,
                    'password' => md5($password)
                ];

                $info = M('user')->where($where)->find();
                if($info){
                    $res = M('user')->where($where)->save(['password' => md5($new_password)]);
                    if($res){
                        $number = M('user')->where(['mobile' => $mobile])->getField('number');
                        M('account')->where(['userid' => $number])->setField('password',md5(md5($password).$number));

                        return api_return(1,'修改密码成功');
                    }else{
                        return api_return(2,'修改密码失败');
                    }
                }else{
                    return api_return(2,'原始密码错误');
                }
            }else{
                return api_return(2,'账号不存在');
            }
        }
    }

    /**
     * 忘记密码
     * */
    public function forget_pwd(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $mobile = $input['mobile'];
            $code = $input['code'];
            $password = $input['password'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($mobile)) return api_return(2,'请输入账号');
            if(empty($password)) return api_return(2,'请输入新密码');

            $sms = M('sms_code')->where(array('mobile'=>$mobile))->order('create_time desc')->limit(1)->find();
            if (!$sms) return api_return(2,'该手机号码未发送验证码');
            if ($sms['failure_time'] < time()) return api_return(2,'验证码已失效');
            if ($code != $sms['code']) return api_return(2,'验证码错误');

            $res = M('user')->where(['mobile' => $mobile])->setField(['password' => md5($password)]);
            if($res){
                return api_return(1,'修改密码成功');
            }else{
                return api_return(2,'修改密码失败');
            }
        }
    }

    /**
     * 才艺类型
     * */
    public function skill_categroy(){
        $list = M('skill')->where(['status' => 1])->select();
        return $list;
    }

    /**
     * 关注/取消关注
     * */
    public function concern_zb(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];//用户id
            $cuid = $input['cuid'];//主播id
            $status = $input['status'];//1：关注；2：取消关注

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'您还未登录');
            if(empty($cuid)) return api_return(2,'请传入主播id');
            if(empty($status)) return api_return(2,'请传入操作类型');
            if($uid == $cuid) return api_return(2,'不能关注自己');

            $where = ['uid' => $uid, 'cuid' => $cuid];
            if($status == 1){
                $count = M('concern')->where($where)->count();
                //关注
                if($count > 0){
                    //之前关注过，此时关注只是修改状态
                    $res = M('concern')->where($where)->save(['status' => $status,'create_time' => time()]);
                }else{
                    $data = [
                        'uid' => $uid,
                        'cuid' => $cuid,
                        'status' => $status,
                        'create_time' => time()
                    ];
                    $res = M('concern')->add($data);
                }
                if($res){
                    M('user')->where(['id' => $cuid])->setInc('funs_num');
                    M('user')->where(['id' => $uid])->setInc('concern_num');
                    return api_return(1,'关注成功');
                }else{
                    return api_return(2,'关注失败');
                }
            }else{
                //取消关注
                $res = M('concern')->where($where)->setField(['status' => $status]);
                if($res){
                    M('user')->where(['id' => $cuid])->setDec('funs_num');
                    M('user')->where(['id' => $uid])->setDec('concern_num');
                    return api_return(1,'取消关注成功');
                }else{
                    return api_return(2,'取消关注失败');
                }
            }
        }

    }

    /**
     * 在线观众列表
     * */
    public function viewer_list(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $type = $input['type'];//1：在线观众，2：管理员
            $n = $input['n'];
            $num = $input['num'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($type)) return api_return(2,'请传入查询类型');

            if($type == 1){
                $where = ['v.auid' => $auid,'v.is_room' => 1];//在线观众条件
            }else{
                $where = ['v.auid' => $auid,'v.is_manager' => 1];//管理员列表条件
            }

            $offset = ($n-1)*$num;
            $list = M('viewer')->alias('v')
                ->join('zb_user u ON v.vuid = u.id')
                ->field('u.id,u.nickname,u.exp,v.is_manager,v.status')
                ->where($where)
                ->limit($offset,$num)
                ->order('u.exp desc')
                ->select();

            if($list){
                foreach($list as $k => $v){
                    $list[$k]['ID'] = $v['id'];
                    $list[$k]['is_status'] = $v['status'];
                    $list[$k]['avatar_img'] = get_avatar($v['id']);//用户头像
                    $gz_info = gz_rank($v['id']);//贵族图标
                    $list[$k]['gz_img'] = $gz_info['img']?$gz_info['img']:'';
                    $list[$k]['rank'] = exp_rank($v['exp']);
                    unset($list[$k]['exp']);
                    unset($list[$k]['id']);
                }
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }

        }
    }

    /**
     * 商品评价
     * */
    public function comment(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                $input = I('post.');
            }

            $key = $input['key'];
            $gid = $input['gid'];//商品id
            $order = $input['order'];//订单号
            $uid = $input['uid'];//用户id
            $star = $input['star'];//评星等级
            $content = $input['content'];//评论内容

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($gid)) return api_return(2,'请传入商品id');
            if(empty($order)) return api_return(2,'请传入订单号');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($star)) return api_return(2,'请传入评星等级');

            $count = M('order')->where(['order_sn' => $order])->count();

            if($count > 0){
                $is_commont = M('comment')->where(['order' => $order, 'uid' => $uid])->count();

                if($is_commont > 0){
                    return api_return(2,'该订单已经评价');
                }else{

                    //上传多图
                    $file = $_FILES['imgs'];
                    if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                        mkdir("Uploads/Picture/" . date("Y-m-d"));
                    }

                    $imgid = array();
                    for ($i = 0; $i < count($file['tmp_name']); $i++) {
                        $str = stristr($file['name'][$i], '.');
                        if ($str != '') {
                            $path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . $i . "comment" . $uid . $str;
                        } else {
                            $path = '';
                        }

                        if ($path != '') {
                            if (copy($file['tmp_name'][$i], $path)) {
                                $imgurl['path'] = "/" . $path;
                                $imgurl['status'] = 1;
                                $imgurl['create_time'] = time();
                                $picture_id = D('picture')->add($imgurl);
                                if ($picture_id) {
                                    $imgid[] = $picture_id;
                                }
                            } else {
                                return api_return(2,'提交失败');
                            }
                        }
                    }
                    $imgs = implode(',', $imgid);

                    $data = [
                        'gid' => $gid,
                        'order' => $order,
                        'uid' => $uid,
                        'star' => $star,
                        'content' => $content,
                        'imgs' => $imgs,
                        'create_time' => time()
                    ];
                    $res = M('comment')->add($data);
                    if($res){
                        $where['order_sn'] = $order;
                        $data['order_status'] = 5;
                        M('order')->where($where)->save($data);

                        return api_return(1,'评价成功');
                    }else{
                        return api_return(2,'评价失败');
                    }
                }

            }else{
                return api_return(2,'该订单不存在');
            }
        }
    }

    /**
     * 评价列表
     * */
    public function comment_list(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $gid = $input['gid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($gid)) return api_return(2,'请传入商品id');

            $offset = ($n-1)*$num;
            $list = M('comment')->alias('c')
                ->field('c.order,c.star,c.content,c.create_time,u.id,u.nickname')
                ->join('zb_user u ON c.uid = u.id')
                ->where(['gid' => $gid])
                ->limit($offset,$num)
                ->order('c.create_time desc')
                ->select();

            foreach($list as $k => $v){
                $list[$k]['create_time'] = date('Y-m-d H:i',$v['create_time']);
                $list[$k]['avatar_img'] = get_avatar($v['id']);
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 查看评价
     * */
    public function look_comment(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $order_sn = $input['order_sn'];//订单号

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            if($order_sn){
                $id = M('comment')->where(['order' => $order_sn])->getField('id');
            }else{

            }
            $info = M('comment')->where(['id' => $id])->find();
            if(!$info) return api_return(2,'暂无评价');

            $info['nickname'] = M('user')->where(['uid' => $info['uid']])->getField('nickname');
            $info['avatar_img'] = get_avatar($info['uid']);
            $info['create_time'] = date('Y-m-d H:i',$info['create_time']);
            $info['pictures'] = get_pictrues($info['imgs']);

            if($info){
                return api_return(1,'获取数据成功',$info);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /****************公共接口部分********************/


    /******************支付接口*********************/

    /**
     * 钻石充值页面
     * */
    public function goods_data(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $gid = $input['gid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $info = M('user')->field('zs_blance,zd_blance')->where(['uid' => $uid])->find();
            $list = M('diamond')->select();//钻石商品

            if($gid){
                $gift_info = M('giftbag')->field('price,zs_num')->where(['id' => $gid, 'type' => 1])->find();
                if($gift_info){
                    $data = [
                        'id' => '9999',
                        'num' => $gift_info['zs_num'],
                        'price' => $gift_info['price']
                    ];
                    $list[count($list)] = $data;
                }else{
                    return api_return(2,'礼包错误');
                }
            }

            $wxts = M('document_wxts')->where(['types' => 1])->order('id desc')->find();

            $data = [
                'info' => $info,
                'list' => $list?$list:[],
                'wxts' => $wxts['content']?$wxts['content']:''
            ];

            return api_return(1,'获取数据成功',$data);
        }
    }

    /**
     * 立即付款
     * 点击立即付款生成订单号
     * */
    public function commit_order(){
        if (IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $price = $input['price'];
            $zf_type = $input['zf_type'];
            $goods_id = $input['goods_id'];
            $style = isset($input['style']) ? true : false;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($zf_type)) return api_return(2, '请传入支付方式');

            if($style){
                //礼包充值
                $data = [
                    'order_sn' => date('YmdH').rand(10000,99999),
                    'uid' => $uid,
                    'zs_num' => C('PECK_ZSNUM'),
                    'zd_num' => 0,
                    'price' => C('PECK_PRICE'),
                    'zf_type' => $zf_type,
                    'create_time' => time()
                ];
                $res = M('recharge')->add($data);
                $order_sn = M('recharge')->where(['uid' => $uid])->order('create_time desc')->getField('order_sn');
            }else{
                if(empty($goods_id)){
                    if(empty($price)) return api_return(2, '请传入金额');
                    $ratio = C('RECHARGE');//充值比例
                    $zs_num = $price*$ratio;
                    $zd_num = $zs_num/2;
                }elseif(empty($price)){
                    if(empty($goods_id)) return api_return(2, '请传入商品id');
                    $goods_info = M('diamond')->where(['id' => $goods_id])->find();
                    $price = $goods_info['price'];
                    $zs_num = $goods_info['num'];
                    $zd_num = $zs_num/2;
                }

                $count = M('recharge')->where(['uid' => $uid])->count();

                $data = [
                    'order_sn' => date('YmdH').rand(10000,99999),
                    'uid' => $uid,
                    'zs_num' => $zs_num,
                    'zd_num' => $zd_num,
                    'price' => $price,
                    'zf_type' => $zf_type,
                    'create_time' => time()
                ];

                if($count > 0){
                    unset($data['zd_num']);
                    $res = M('recharge')->add($data);
                    $order_sn = M('recharge')->where(['uid' => $uid])->order('create_time desc')->getField('order_sn');
                }else{
                    //首充送钻豆
                    $res = M('recharge')->add($data);
                    $order_sn = M('recharge')->where(['uid' => $uid])->order('create_time desc')->getField('order_sn');
                }
            }

            if($res && $order_sn){
                return api_return(1, '订单生成成功', $order_sn);
            }else{
                return api_return(2, '订单生成失败');
            }
        }
    }

    /******************支付宝支付**********************/
    public function pay_z() {
        $json_data = php_input();
        if(!is_null(json_decode($json_data))){
            //json数据，IOS请求数据
            $input = json_decode($json_data,true);
        }else{
            //非json数据，安卓请求数据
            parse_str($json_data, $input);
        }

        $key = $input['key'];
        $price = $input['price'];
        $order_sn = $input['order_sn'];

        if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
        if(empty($price)) return api_return(2,'订单金额错误');
        if(empty($order_sn)) return api_return(2,'订单号错误');

        $body = "直播钻石充值";
        $subject = "直播钻石充值";

        vendor('alipay.AopSdk');
        $aop = new \AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";//正式环境
        /*$aop->gatewayUrl = "https://openapi.alipaydev.com/gateway.do";沙箱环境*/
        $aop->appId = '***************';
        C('PAY_ALIPAY_APPID');/*正式环境APPID*/
        /*$aop->appId = '2017102609534803';C('PAY_ALIPAY_APPID');沙箱环境APPID*/
        $aop->rsaPrivateKey = '*******************************';
        /*C('PAY_ALIPAY_PRIVATE_KEY');请填写开发者私钥去头去尾去回车，一行字符串*/
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = '******************************';
        /*C('PAY_ALIPAY_PUBLIC_KEY');请填写支付宝公钥，一行字符串*/
        /*实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay*/
        $request = new \AlipayTradeAppPayRequest();

        $bizcontent = "{\"body\":\"$body\",\"subject\": \"$subject\",\"out_trade_no\": \"" . $order_sn . "\",\"timeout_express\": \"30m\",\"total_amount\": \"" . $price . "\",\"product_code\":\"QUICK_MSECURITY_PAY\"}";

        //print_r($bizcontent);exit;
        $notify_url = 'http://www.live.com/index.php?s=/Home/dhl/order_alipay';
        $request->setNotifyUrl($notify_url);
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
        /*htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题*/

        $this->success_alipay('提交成功', array('orderStr' => $response));
        /*就是orderString 可以直接给客户端请求，无需再做处理。*/
    }

    //回调地址 业务逻辑代码
    public function order_alipay(){
        vendor('alipay.AopSdk');
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = '************************************';
        //请填写支付宝公钥，一行字符串
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
//            file_put_contents('text1.text',json_encode($_POST));
            if($_POST['trade_status'] == 'TRADE_SUCCESS'){//判断支付宝支付成功
                //这里写修改订单状态代码
                $order_sn = $_POST["out_trade_no"];
                M('recharge')->where(['order_id' => $order_sn])->save(['status' => 1,'pay_time' => time()]);

                //支付成功后用户钻石增加
                $order_info = M('recharge')->where(['order_id' => $order_sn])->find();

                M('user')->where(['id' => $order_info['uid']])->setInc('zs_blance',$order_info['zs_num']);
                if($order_info['zd_num'] > 0) M('user')->where(['id' => $order_info['uid']])->setInc('zd_blance',$order_info['zd_num']);

            }else{
                //支付失败返回错误提示
            }
        }
    }

    /******************支付宝支付**********************/


    /******************微信支付**********************/

    public function wxpay() {
        header("Access-Control-Allow-Origin: *");

        $json_data = php_input();
        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

        $key = $input['key'];
        $price = $input['price'];
        $order_sn = $input['order_sn'];

        if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
        if(empty($price)) return api_return(2,'订单金额错误');
        if(empty($order_sn)) return api_return(2,'订单号错误');

        $body = "直播钻石充值";

        $data = array(
            'body' => $body,
            'out_trade_no' => $order_sn,
            'total_fee' => $price*100,
            'spbill_create_ip' => get_client_ip(),
        );

        vendor('Service.WxpayService#class');
        $wxpay = new \WxpayService;
        $notify_url = "http://www.live.com/index.php?s=/Home/dhl/order_wxpay";

        $wxpay->setNotifyUrl($notify_url);//设置异步通知地址
        $xml_data = $wxpay->sendRequest($data);  //发送请求
        $postObj = $wxpay->xmlToObject($xml_data);   //解析返回数据
        if ($postObj === false) {
            $data["result"]=2;
            $data["error"]="支付错误";
            $this->ajaxReturn($data);
        } elseif ($postObj->return_code == 'FAIL') {
            $data["result"]=2;
            $data["error"]=$postObj->return_msg;
            $this->ajaxReturn($data);
        } else {
            $resignData = array(
                'app_id' => $postObj->appid,
                'mch_id' => $postObj->mch_id,
                'prepay_id' => $postObj->prepay_id,
                'nonce_str' => $postObj->nonce_str,
                'timestamp' => NOW_TIME,
                'package_str' => 'Sign=WXPay'
            );
            $sign = $wxpay->getClientPay($resignData);
            $resignData['sign'] = $sign;

            $data["result"]=1;
            $data["orderStr"]=json_encode($resignData);
            $this->ajaxReturn($data);
            /*$this->success('提交成功', array('orderStr' => json_encode($resignData)));*///就是orderString 可以直接给客户端请求，无需再做处理。
        }
    }

    //微信支付验证
    public function order_wxpay() {
        vendor('Service.WxpayService#class');
        $wxpay = new \WxpayService;
        $obj = $wxpay->getNotifyData();
        if ($obj === false) {
            exit;
        }
        if ($obj) {
            $data = array(
                'appid' => $obj->appid,
                'mch_id' => $obj->mch_id,
                'nonce_str' => $obj->nonce_str,
                'result_code' => $obj->result_code,
                'openid' => $obj->openid,
                'trade_type' => $obj->trade_type,
                'bank_type' => $obj->bank_type,
                'total_fee' => $obj->total_fee,
                'cash_fee' => $obj->cash_fee,
                'transaction_id' => $obj->transaction_id,
                'out_trade_no' => $obj->out_trade_no,
                'time_end' => $obj->time_end
            );
            $sign = $wxpay->getSign($data);
            if ($sign == $obj->sign) {
                $order_sn = $obj->out_trade_no;//获取订单号

                $res = M('recharge')->where(['order_id' => $order_sn])->save(['status' => 1,'pay_time' => time()]);

                //支付成功后用户钻石增加
                $order_info = M('recharge')->where(['order_id' => $order_sn])->find();

                M('user')->where(['id' => $order_info['uid']])->setInc('zs_blance',$order_info['zs_num']);
                if($order_info['zd_num'] > 0) M('user')->where(['id' => $order_info['uid']])->setInc('zd_blance',$order_info['zd_num']);

                if($res){
                    $reply = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    echo $reply;
                    die();
                }else{
                    $reply = "<xml><return_code><![CDATA[ERROR]]></return_code><return_msg><![CDATA[{$res['error']}]]></return_msg></xml>";
                    echo $reply;
                    die();
                }
            }
        }
    }
    /******************微信支付**********************/

    /******************支付接口*********************/

    /**
     * 钻石充值记录
     * */
    public function recharge_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $offset = ($n-1)*$num;
            $list = M('recharge')->field('zs_num,zf_type,pay_time')->where(['uid' => $uid,'status' => 1])->limit($offset,$num)->order('pay_time desc')->select();

            foreach($list as $k => $v){
                $list[$k]['pay_time'] = date('m-d',$v['pay_time']);
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'获取数据失败',[]);
            }
        }
    }

    /**
     * 个人中心
     * */
    public function person_info(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $info = M('user')->field('id,nickname,concern_num,funs_num,profit,is_anchor,rz_status,zs_blance,zd_blance,exp')->where(['id' => $uid])->find();
            $info['avatar_img'] = get_avatar($uid);
            $info['user_count'] = count(user_concern_mess_count($uid));
            $info['rank'] = exp_rank($info['exp']);

            $gz_info = gz_rank($uid);
            $info['gz_img'] = $gz_info['img'];
            $info['day'] = $gz_info['day'];

            if($info){
                return api_return(1,'获取数据成功',$info);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 关注列表
     * */
    public function concern(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $u_lng = $input['u_lng']?$input['u_lng']:0;
            $u_lat = $input['u_lat']?$input['u_lat']:0;
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $offset = ($n-1)*$num;

            //已关注主播id列表
            $cuid_list = M('concern')->alias('c')
                ->field('c.cuid')
                ->join('zb_anchor as a ON c.cuid = a.auid')
                ->where(['c.uid' => $uid,'c.status' => 1])
                ->limit($offset,$num)
                ->order('a.is_show desc,c.create_time desc')
                ->select();

            if($cuid_list){
                $cuids = array_column($cuid_list,'cuid');

                $users = rooms_data('concern',$cuids);

                if($users){
                    foreach($users as $k => $v){
                        $info = M('user')->field('lng,lat')->where(['id' => $v['auid']])->find();
                        $users[$k]['distance'] = getDistance_map($v['lng'],$v['lat'],$u_lng,$u_lat);
                    }
                }

                if($users){
                    return api_return(1,'获取数据成功',$users);
                }else{
                    return api_return(1,'暂无更多数据',[]);
                }
            }else{
                return api_return(1,'暂无更多数据',[]);
            }

        }
    }

    /**
     * 最近观看
     * */
    public function lately_look(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $offset = ($n-1)*$num;
            $list = M('lately')->field('cuid')->where(['uid' => $uid, 'is_delete' => 0])->limit($offset,$num)->order('create_time desc')->select();

            if($list){
                $ids = '';
                foreach($list as $k => $v){
                    $ids .= $v['cuid'].',';
                }
                $ids = substr($ids,0,-1);

                $room_list = rooms_data('lately',$uid);

                foreach($room_list as $k => $v){
                    $room_list[$k]['avatar_img'] = get_avatar($v['auid']);
                    $room_list[$k]['is_concern'] = is_concern($uid,$v['auid']);
                }
            }else{
                return api_return(1,'暂无更多数据',[]);
            }

            if($room_list){
                return api_return(1,'获取数据成功',$room_list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 拉黑/取消拉黑
     * */
    public function black(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];//主播id
            $buid = $input['buid'];//用户id
            $status = $input['status'];//1:拉黑；2：取消拉黑

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入主播id');
            if(empty($buid)) return api_return(2,'请传入用户id');

            if($status == 1){
                $is_black = 1;
            }else{
                $is_black = 0;
            }

            $data = [
                'uid' => $uid,
                'buid' => $buid,
                'is_black' => $is_black,
                'create_time' => time()
            ];

            $count = M('concern')->where(['uid' => $uid, 'buid' => $buid])->count();

            if($count > 0){
                //之前已经被拉黑过
                $res = M('concern')->where(['uid' => $uid, 'cuid' => $buid])->save(['is_black' => $is_black, 'create_time' => time()]);
            }else{
                //第一次被拉黑
                $res = M('concern')->add($data);
            }
            if($res){
                $number = M('user')->where(['id' => $uid])->getField('number');
                $b_number = M('user')->where(['id' => $buid])->getField('number');
                $number_arr = [$b_number];
                $send_data = [
                    'From_Account' => $number,
                    'To_Account' => $number_arr
                ];
                if($status == 1){
                    //拉黑
                    $json = add_black($number,$number_arr,json_encode($send_data));
                    $result = json_decode($json,true);
                    if($result['ActionStatus'] == 'OK'){
                        return api_return(1, '操作成功');
                    }else{
                        return api_return(2, '云通信拉黑失败');
                    }
                }else{
                    //取消拉黑
                    $json = delete_black($number,$number_arr,json_encode($send_data));
                    $result = json_decode($json,true);
                    if($result['ActionStatus'] == 'OK'){
                        return api_return(1, '操作成功');
                    }else{
                        return api_return(2, '云通信取消拉黑失败');
                    }
                }
            }else{
                return api_return(2, '操作失败');
            }
        }
    }

    /**
     * 禁言
     * */
    public function excuse(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $uid = $input['uid'];//用户id
//            $room_id = $input['room_id'];//房间号
            $type = $input['type']?$input['type']:1;//1:禁言；2：取消禁言

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($uid)) return api_return(2,'请传入用户id');
//            if(empty($room_id)) return api_return(2,'请传入房间id');

//            if($type == 2){
//                //取消禁言
//                $time = 0;
//            }else{
//                //禁言
//                $time = 172800;//禁言时间（默认2天）
//            }

            $is_manager = M('viewer')->where(['auid' => $auid, 'vuid' => $uid])->getField('is_manager');
            if($is_manager == 1) return api_return(2,'禁言失败，不能对管理员禁言');

            $status = M('viewer')->where(['auid' => $auid, 'vuid' => $uid])->getField('status');
            if($status == 2 && $type == 1) return api_return(2,'禁言失败，该用户已被禁言');

//            $number = M('user')->where(['id' => $uid])->getField('number');

//            $url = "https://console.tim.qq.com/v4/group_open_http_svc/forbid_send_msg?usersig=".get_UserSig($room_id,true)."&identifier=".C('YUN_USERID')."&sdkappid=".C('YUN_SDKAPPID')."&random=".rand(100000,999999)."&contenttype=json";
//            $json_data = '{
//                "GroupId": "'.$room_id.'",
//                "Members_Account": [
//                    "'.$number.'"
//                ],
//                "ShutUpTime": '.$time.'
//            }';
//
//            $res = curl($url,$json_data);
//            $res = json_decode($res,true);

//            if($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0){
                //调用腾讯云禁言成功
                if($type == 1){
                    $result = M('viewer')->where(['auid' => $auid, 'vuid' => $uid])->setField('status',2);
                }elseif($type == 2){
                    $result = M('viewer')->where(['auid' => $auid, 'vuid' => $uid])->setField('status',1);
                }

                if($type == 1){
                    if($result){
                        return api_return(1,'禁言成功');
                    }else{
                        return api_return(2,'禁言失败');
                    }
                }else{
                    if($result){
                        return api_return(1,'取消禁言成功');
                    }else{
                        return api_return(2,'取消禁言失败');
                    }
                }
//            }else{
//                return api_return(2,'API调用失败');
//            }

        }
    }

    /**
     * 黑名单列表
     * */
    public function black_list(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];//主播id
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;
            $nickname = $input['nickname']?$input['nickname']:'';
            if($nickname) $map['u.nickname'] = array('like','%'.$nickname.'%');

            $map['c.cuid'] = array('eq',$uid);
            $map['c.status'] = array('eq',1);

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入主播id');

            $offset = ($n-1)*$num;
            $list = M('concern')->alias('c')
                ->join('zb_user u ON c.uid = u.id')
                ->field('u.id,u.nickname,u.avatar_img,c.is_black')
                ->where($map)
                ->order('c.is_black asc,c.create_time desc')
                ->limit($offset,$num)
                ->select();

            foreach($list as $k => $v){
                $list[$k]['avatar_img'] = get_avatar($v['id']);
            }

            if($list){
                return api_return(1, '获取数据成功', $list);
            }else{
                return api_return(1, '暂无更多数据', []);
            }
        }
    }

    /**
     * 贡献数
     * */
    public function profit(){

        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $profit = M('user')->where(['id' => $uid])->getField('profit');

            $data = ['profit' => $profit];

            return api_return(1,'获取数据成功',$data);
        }
    }

    /**
     * 贡献数兑换钻石
     * */
    public function exchange_page(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $wxts = M('document_wxts')->where(['types' => 2])->order('id desc')->find();

            return api_return(1,'获取数据成功',$wxts['content']);
        }
    }

    /**
     * 贡献数兑换钻石
     * */
    public function profit_exchange(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $zs_num = $input['zs_num'];
            $profit_to_zs = C('PROFIT_TO_ZS');//贡献数兑换钻石比例

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($zs_num)) return api_return(2,'请输入兑换钻石数');

            $res1 = M('user')->where(['id' => $uid])->setInc('zs_blance',$zs_num);
            $res2 = M('user')->where(['id' => $uid])->setDec('profit',$zs_num/$profit_to_zs);

            $profit = M('user')->where(['id' => $uid])->getField('profit');

            if($profit >= $zs_num/$profit_to_zs){
                if(!$res1 && !$res2){
                    return api_return(2,'兑换钻石失败');
                }else{
                    return api_return(1,'兑换钻石成功');
                }
            }else{
                return api_return(2,'收益数不足');
            }
        }
    }

    /**
     * 贡献数提现
     * */
    public function profit_reflect(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $price = $input['price'];
            $wechat = $input['wechat'];
            $username = $input['username'];
            $profit_to_rmb = C('PROFIT_TO_RMB');//贡献数兑换钻石比例

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($price)) return api_return(2,'请输入提现金额');
            if(empty($wechat)) return api_return(2,'请输入微信号');
            if(empty($username)) return api_return(2,'请输入微信名');

            $data = [
                'uid' => $uid,
                'username' => $username,
                'price' => $price,
                'profit' => $price,
                'wechat' => $wechat,
                'create_time' => time(),
            ];

            $profit = M('user')->where(['id' => $uid])->getField('profit');

            $run_cash = C('RUN_CASH');
            if($profit >= $run_cash){
                if($profit >= $price){
                    M('user')->where(['id' => $uid])->setDec('profit',$price/$profit_to_rmb);
                    $res = M('withdrawals')->add($data);
                    if($res){
                        return api_return(1,'申请提交成功');
                    }else{
                        return api_return(2,'申请提交失败');
                    }
                }else{
                    return api_return(2,'贡献数不足');
                }
            }else{
                return api_return(2,'满'.$run_cash.'贡献度才能提现');
            }

        }
    }

    /**
     * 提现记录
     * */
    public function reflect_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $offset = ($n-1)*$num;
            $list = M('withdrawals')->where(['uid' => $uid])->limit($offset,$num)->select();

            foreach($list as $k => $v){
                $list[$k]['create_time'] = date('Y-m-d H:i',$v['create_time']);
            }
            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }

        }
    }

    /********************贵族模块**************************/
    /**
     * 贵族分类
     * */
    public function gz_level_list(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            //贵族列表信息
            $list = M('gz_level')->field('id,name,img,zsnum')->select();
            foreach($list as $k => $v){
                $list[$k]['img'] = get_img($v['img']);
            }

            //开通月数数据
            $time_list = M('gz_time')->field('name,month')->select();

            $content = M('document_tqsm')->where(['types' => 2])->getField('content');//特权说明

            if($list){
                $data = [
                    'list' => $list,
                    'time' => $time_list,
                    'content' => $content
                ];
            }else{
                $data = [
                    'list' => [],
                    'time' => [],
                    'content' => $content
                ];
            }

            if($list){
                return api_return(1,'获取数据成功',$data);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 贵族开通时长
     * */
    public function gz_time(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $level_id = $input['level_id'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($level_id)) return api_return(2,'请传入分类id');

            $list = M('gz_time')->field('month,zsnum all_zsnum,name')->where(['level_id' => $level_id])->select();

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 开通贵族
     * 开通贵族返等额的钻豆
     * 续费贵族可升级但是不可降级，升级之后低等级贵族直接作废
     * */
    public function open_gz(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $level_id = $input['level_id'];
            $month = $input['month'];
            $zsnum = $input['zsnum'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($level_id)) return api_return(2,'请传入等级id');
            if(empty(is_numeric($month))) return api_return(2,'请传入开通时长');
            if(empty(is_numeric($zsnum))) return api_return(2,'请传入所需钻石数');

            $zs_blance = M('user')->where(['id' => $uid])->getField('zs_blance');
            $all_zsnum = $zsnum*$month;

            if($zs_blance < $all_zsnum) return api_return(2,'账户钻石余额不足');

            $gz_info = M('gz_notes')->field('level_id,end_time')->where(['uid' => $uid])->order('create_time desc')->find();
            if($gz_info['end_time'] > time()){
                //贵族身份
                if($level_id < $gz_info['level_id']){
                    return api_return(2,'您当前贵族身份未过期，不可降级');
                }
            }

            $end_time = M('gz_notes')->where(['uid' => $uid,'level_id' => $level_id])->order('create_time desc')->getField('end_time');

            $end_time = isset($end_time)?$end_time:0;

            $expire_time = expire($month);
            $open_time = $expire_time - time();//开通时长（时间戳）

            if($end_time == 0 || $end_time < time()){
                $end_time = time() + $open_time;
            }else{
                $end_time = $end_time+$open_time;
            }

            M('user')->where(['id' => $uid])->setDec('zs_blance',$all_zsnum);
            M('user')->where(['id' => $uid])->setInc('zd_blance',$all_zsnum);//赠送等额钻豆

            $data = [
                'uid' => $uid,
                'level_id' => $level_id,
                'month' => $month,
                'zsnum' => $all_zsnum,
                'end_time' => $end_time,
                'create_time' => time()
            ];

            $user_exp = C('USER_EXP')*$all_zsnum;
            M('user')->where(['id' => $uid])->setInc('exp',$user_exp);

            $res = M('gz_notes')->add($data);
            if($res){
                $number = M('user')->where(['id' => $uid])->getField('number');
                $json = im_set_attr_vip($number,$level_id);
                $result = json_decode($json,true);
                if($result['ActionStatus'] == 'OK'){
                    return api_return(1,'开通贵族成功');
                }else{
                    M('user')->where(['id' => $uid])->setInc('zs_blance',$all_zsnum);
                    M('user')->where(['id' => $uid])->setDec('zd_blance',$all_zsnum);//赠送等额钻豆
                    M('user')->where(['id' => $uid])->setDec('exp',$user_exp);
                    M('gz_notes')->where(['id' => $res])->delete();
                    return api_return(2,'开通贵族失败，设置用户vip属性失败');
                }
            }else{
                return api_return(2,'开通贵族失败');
            }
        }
    }
    /********************贵族模块**************************/

    /*****************守护模块**********************/

    /**
     * 守护分类
     * */
    public function sh_level_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'用户id不能为空');

            //守护等级分类
            $list = M('sh_level')->select();
            foreach($list as $k => $v){
                $list[$k]['img'] = get_img($v['img']);
            }

            //守护时间分类
            $time_list = M('sh_time')->field('name,month')->select();
            $count = M('sh_notes')->where(['uid' => $uid, 'sh_time' => 0])->count();

            $free = [
                'name' => '7天免费体验',
                'month' => 0
            ];

            if($count == 0) array_unshift($time_list,$free);

            $content = M('document_tqsm')->where(['types' => 1])->getField('content');//特权说明

            if($list){
                $data = [
                    'list' => $list,
                    'time' => $time_list,
                    'content' => $content
                ];
            }else{
                $data = [
                    'list' => [],
                    'time' => [],
                    'content' => $content
                ];
            }


            if($list){
                return api_return(1,'获取数据成功',$data);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }


    /**
     * 开通时间与守护等级联动
     * */
    public function sh_time_check(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $month = $input['month'];

            $sh_price = C('SH_PRICE');//开通守护单月所需钻石数

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($month) && $month != 0) return api_return(2,'请传入开通时间');

            $sh_info = M('sh_level')->field('id level_id,name')->where('month <= '.$month)->order('month desc')->find();

            $data['level_id'] = $sh_info['level_id'];
            $data['name'] = $sh_info['name'];
            $data['month'] = $month;
            $data['all_zsnum'] = $month*$sh_price;

            return api_return(1,'获取数据成功',$data);
        }
    }

    /**
     * 开通守护
     * 开通守护之后，在守护未过期之前，不可再次开通；守护等级不累积
     * */
    public function open_sh(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];
            $month = $input['month'];
            $level_id = $input['level_id'];
            $zsnum = $input['zsnum'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($level_id)) return api_return(2,'请传入守护等级id');
            if(empty(is_numeric($month))) return api_return(2,'请传入开通时长');
            if(empty(is_numeric($zsnum))) return api_return(2,'请传入所需钻石数');

            $sh_end_time = M('sh_notes')->where(['uid' => $uid, 'auid' => $auid])->getField('end_time');
            if($sh_end_time > time()) return api_return(2,'守护未到期，无法再次开通');

            $zs_blance = M('user')->where(['id' => $uid])->getField('zs_blance');
            if($zs_blance < $zsnum) return api_return(2,'钻石余额不足');

            //开通时长
            if($month){
                $expire_time = expire($month);
                $open_time = $expire_time - time();
            }else{
                //7天体验
                $open_time = 7*3600*24;
            }

            $end_time = time()+$open_time;//守护到期时间

            $data = [
                'uid' => $uid,
                'auid' => $auid,
                'level_id' => $level_id,
                'sh_time' => $month,
                'zsnum' => $zsnum,
                'create_time' => time(),
                'end_time' => $end_time
            ];

            $user_exp = C('USER_EXP')*$zsnum;//用户获得的经验值
            $zb_exp = C('ZB_EXP')*$zsnum;//主播获得的经验值

            M('user')->where(['id' => $uid])->setDec('zs_blance',$zsnum);
            M('user')->where(['id' => $uid])->setInc('exp',$user_exp);
            M('user')->where(['id' => $auid])->setInc('exp',$zb_exp);

            $res = M('sh_notes')->add($data);
            if($res){
                return api_return(1,'开通守护成功');
            }else{
                return api_return(1,'开通守护失败');
            }

        }
    }
    /*public function open_sh(){
        if(IS_POST){
            $input = I('post.');

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];
            $month = $input['month'];
            $level_id = $input['level_id'];
            $zsnum = $input['zsnum'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($level_id)) return api_return(2,'请传入守护等级id');
            if($month != 0){
                if(empty($month)) return api_return(2,'请传入开通时长');
                if(empty($zsnum)) return api_return(2,'请传入所需钻石数');
            }

            $user_info = M('user')->field('id,zs_blance')->where(['id' => $uid])->find();
            if($user_info['zs_blance'] < $zsnum) return api_return(2,'钻石余额不足');
            if(empty($user_info['id'])) return api_return(2,'系统错误');

            $month = isset($month)?$month:0;
            //开通时长
            if($month){
                $expire_time = expire($month);
                $open_time = $expire_time - time();
            }else{
                //7天体验
                $open_time = 7*3600*24;
            }

            $end_time = M('sh_notes')->where(['uid' => $uid, 'auid' => $auid])->order('create_time desc')->getField('end_time');

            $end_time = isset($end_time)?$end_time:0;
            if($end_time == 0 || $end_time < time()){
                //续费
                $end_time = time()+$open_time;
            }else{
                //到期
                $end_time = $end_time+$open_time;
            }

            $data = [
                'uid' => $uid,
                'auid' => $auid,
                'level_id' => $level_id,
                'sh_time' => $month,
                'zsnum' => $zsnum,
                'create_time' => time(),
                'end_time' => $end_time
            ];

            $user_exp = C('USER_EXP')*$zsnum;//用户获得的经验值
            $zb_exp = C('ZB_EXP')*$zsnum;//主播获得的经验值

            M('user')->where(['id' => $uid])->setDec('zs_blance',$zsnum);
            M('user')->where(['id' => $uid])->setInc('exp',$user_exp);
            M('user')->where(['id' => $auid])->setInc('exp',$zb_exp);

            $res = M('sh_notes')->add($data);
            if($res){
                return api_return(1,'开通守护成功');
            }else{
                return api_return(1,'开通守护失败');
            }
        }
    }*/

    /**
     * 守护榜列表
     * */
    public function sh_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $map['s.end_time'] = ['gt',time()];
            $map['s.auid'] = ['eq',$auid];

            $top_three = M('sh_notes')->alias('s')
                ->field('s.uid,u.nickname,s.level_id')
                ->join('zb_user u ON s.uid = u.id')
                ->where($map)
                ->order('s.level_id desc,s.create_time asc')
                ->limit(3)
                ->select();

            $offset = ($n-1)*$num+3;
            $list = M('sh_notes')->alias('s')
                ->field('u.id,u.nickname,s.level_id')
                ->join('zb_user u ON s.uid = u.id')
                ->where($map)
                ->order('s.level_id desc,s.create_time asc')
                ->limit($offset,$num)
                ->select();

            foreach($top_three as $k => $v){
                $top_three[$k]['avatar_img'] = get_avatar($v['uid']);
                $sh_info = sh_rank($v['level_id']);
                $top_three[$k]['level_name'] = $sh_info['name'];
                $top_three[$k]['img'] = get_img($sh_info['img']);
            }
            foreach($list as $key => $val){
                $list[$key]['avatar_img'] = get_avatar($val['uid']);
                $sh_info = sh_rank($val['level_id']);
                $list[$key]['level_name'] = $sh_info['name'];
                $list[$key]['img'] = get_img($sh_info['img']);
            }

            $data = [
                'top_three' => $top_three?$top_three:[],
                'list' => $list?$list:[]
            ];

            if(count($data['top_three']) > 0){
                return api_return(1,'获取数据成功',$data);
            }else{
                return api_return(1,'暂无更多数据',$data);
            }
        }

    }

    /*****************守护模块**********************/


    /**
     * 日榜排行
     * */
    public function profit_rank(){
        if(IS_POST){
            $json_data = php_input();

            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $rank_type = $input['rank_type']?$input['rank_type']:1;
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            if($rank_type == 1){
                //日范围
                $start_time = strtotime(date('Y-m-d',time()));
                $end_time = $start_time+60*60*24-1;
            }elseif($rank_type == 2){
                //周范围
                $start_time=mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y'));
                $end_time=mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y'));
            }else{
                //月范围
                $start_time=mktime(0,0,0,date('m'),1,date('Y'));
                $end_time=mktime(23,59,59,date('m'),date('t'),date('Y'));
            }


            $map['s.create_time']  = array('between', $start_time.','.$end_time);

            $offset = ($n-1)*$num;
            $list = M('send_gift')->alias('s')
                ->field('s.uid,u.nickname,u.exp')
                ->join('zb_user u ON s.uid = u.id')
                ->where($map)->where(['s.auid' => $auid])
                ->group('s.uid')
                ->limit($offset,$num)
                ->select();

            $map2['create_time']  = array('between', $start_time.','.$end_time);
            foreach($list as $k => $v){
                $list[$k]['profit'] = M('send_gift')->where($map2)->where(['uid' => $v['uid'],'auid' => $auid])->sum('profit');
                $list[$k]['avatar_img'] = get_avatar($v['uid']);
                $list[$k]['rank'] = exp_rank($v['exp']);
                $gz_info = gz_rank($v['uid']);
                $list[$k]['gz_img'] = $gz_info['img'];
            }

            $list = my_sort($list, 'profit', SORT_DESC);

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /*****************用户端直播间*******************/

    /**
     * 用户端直播间数据显示
     * */
    public function user_side(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $uid = $input['uid']?$input['uid']:0;//用户id（可选）

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $anchor_info = zb_user_info($auid,$uid);//主播信息
            $zb_profit = zb_profit($auid);//主播当前贡献度
            $zb_sh = zb_sh($auid);//主播守护人数
            $singing = singing($auid);//正在唱的歌曲
            $is_gz = zb_gz($uid);//是否是贵族（1：是；2：否）
            $count = M('anchor')->where(['auid' => $auid])->getField('count');

            $number = M('user')->where(['id' => $auid])->getField('number');

            $data = [
                'ID' => $anchor_info['ID']?$anchor_info['ID']:'',
                'avatar_img' => $anchor_info['avatar_img'],
                'nickname' => $anchor_info['nickname']?$anchor_info['nickname']:'',
                'number' => $number?$number:'',
                'is_concern' => $anchor_info['is_concern'],
                'is_sh' => $anchor_info['is_sh'],
                'profit' => intval($zb_profit),
                'sh' => $zb_sh,
                'singing' => $singing,
                'is_gz' => $is_gz,
                'count' => isset($count)?$count:0
            ];

            return api_return(1,'获取数据成功',$data);
        }
    }

    /**
     * 用户端pk直播间数据显示
     * */
    public function user_side_pk(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $uid = $input['uid']?$input['uid']:0;//用户id（可选）

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $anchor_info = zb_user_info($auid,$uid);//主播信息
            $zb_profit = zb_profit($auid);//主播当前贡献度
            $zb_sh = zb_sh($auid);//主播守护人数
            $is_gz = zb_gz($uid);//是否是贵族（1：是；2：否）
            $count = M('anchor')->where(['auid' => $auid])->getField('count');

            $number = M('user')->where(['id' => $auid])->getField('number');

            //pk信息
            $pk_map['uid'] = array('eq',$auid);
            $pk_map['buid'] = array('eq',$auid);
            $pk_map['_logic'] = 'or';
            $map['_complex'] = $pk_map;
            $map['status']  = array('eq',1);
            $pk_info = M('pk')->field('uid,buid,pknum,bpknum,create_time,pk_time')->where($map)->find();
            if($pk_info['uid'] == $auid){
                //当前主播为pk发起者
                $buid = $pk_info['buid'];//对方主播id
                $buid_info = zb_user_info($buid);
                $pknum = $pk_info['pknum'];
                $bpknum = $pk_info['bpknum'];
                $ratio = intval(($pknum/($pknum+$bpknum))*100);
                $b_ratio = intval(100-$ratio);
            }else{
                //当前主播为pk接受者
                $buid = $pk_info['uid'];//对方主播id
                $buid_info = zb_user_info($buid);
                $pknum = $pk_info['bpknum'];
                $bpknum = $pk_info['pknum'];
                $ratio = intval(($pknum/($pknum+$bpknum))*100);
                $b_ratio = intval(100-$ratio);
            }
            if($pk_info){
                $time = ($pk_info['pk_time']*60-(time()-$pk_info['create_time']))*1000;//毫秒
            }else{
                $time = 0;
            }

            $data = [
                'ID' => $anchor_info['ID']?$anchor_info['ID']:'',//房间号
                'avatar_img' => $anchor_info['avatar_img'],
                'nickname' => $anchor_info['nickname']?$anchor_info['nickname']:'',
                'number' => $number?$number:'',
                'is_concern' => $anchor_info['is_concern'],
                'is_sh' => $anchor_info['is_sh'],
                'profit' => intval($zb_profit),
                'sh' => $zb_sh,
                'is_gz' => $is_gz,
                'count' => isset($count)?$count:0,
                'pknum' => $pknum?$pknum:0,
                'ratio' => $ratio?$ratio:0,
                'b_avatar_img' => $buid_info['avatar_img']?$buid_info['avatar_img']:'',
                'b_nickname' => $buid_info['nickname']?$buid_info['nickname']:'',
                'bpknum' => $bpknum?$bpknum:0,
                'b_ratio' => $b_ratio?$b_ratio:0,
                'time' => $time
            ];

            if(empty($pknum) && empty($bpknum)){
                $data['ratio'] = 50;
                $data['b_ratio'] = 50;
            }

            return api_return(1,'获取数据成功',$data);
        }
    }


    /**
     * 点歌列表
     * */
    public function zb_music_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $title = $input['title'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');
            $offset = ($n-1)*$num;

            if(!empty($title)){
                //搜索歌曲
                $map['title'] = array('like','%'.$title.'%');
                $ids = M('music')->field('id')->where($map)->limit($offset,$num)->select();
                $in_ids = array_column($ids,'id');

                if($in_ids){
                    $map['z.music_id'] = array('IN',$in_ids);
                }
            }

            if($title != ''){
                $list = M('zbmusic')->alias('z')
                    ->field('m.id as single_id,m.title,z.music_type,z.zs_num')
                    ->join('zb_music m ON z.music_id = m.id')
                    ->where(['z.auid' => $auid])
                    ->where($map)
                    ->limit($offset,$num)
                    ->select();
            }else{
                $list = M('zbmusic')->alias('z')
                    ->field('m.id as single_id,m.title,z.music_type,z.zs_num')
                    ->join('zb_music m ON z.music_id = m.id')
                    ->where(['z.auid' => $auid])
                    ->limit($offset,$num)
                    ->select();
            }


            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'获取数据失败',[]);
            }
        }
    }

    /**
     * 点歌
     * */
    public function choose_music(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];
            $music_id = $input['music_id'];
            $music_type = $input['music_type'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($music_id)) return api_return(2,'请传入歌曲id');
            if(empty($music_type)) return api_return(2,'请传入歌曲类型');

            $data = [
                'uid' => $uid,
                'auid' => $auid,
                'music_id' => $music_id,
                'music_type' => $music_type,
                'create_time' => time()
            ];

            $zs_num = M('zbmusic')->where(['music_id' => $music_id, 'auid' => $auid])->getField('zs_num');//每首点歌所花费钻石

            $zs_blance = M('user')->where(['id' => $uid])->getField('zs_blance');

            if($zs_blance < $zs_num){
                //用户账户钻石余额不足
                return api_return(2,'账户钻石余额不足');
            }else{
                M('user')->where(['id' => $uid])->setDec('zs_blance',$zs_num);
                $res = M('ydmusic')->add($data);
                if($res){
                    return api_return(1,'点歌成功');
                }else{
                    return api_return(2,'点歌失败');
                }
            }
        }
    }

    /**
     * 点击头像查看主播个人信息
     * */
    public function zb_info(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $info = M('user')->field('nickname,sex,age,city,exp')->where(['id' => $auid])->find();
            $info['avatar'] = get_avatar($auid);//主播头像

            $city = M('district')->where(['id' => $info['city'], 'level' => 2])->getField('name');
            $info['city'] = $city?$city:'';
            $info['concern_count'] = concern_count($auid);

            $send_zs = M('send_gift')->where(['uid' => $auid])->sum('zs_num');
            $send_zs = $send_zs?$send_zs:0;
            $send_zd = M('send_gift')->where(['uid' => $auid])->sum('zd_num');
            $send_zd = $send_zd?$send_zd:0;
            $info['send_gift'] = $send_zs+$send_zd;//赠送礼物钻石价值

            $get_zs = M('send_gift')->where(['auid' => $auid])->sum('zs_num');
            $get_zd = M('send_gift')->where(['auid' => $auid])->sum('zd_num');
            $info['get_gift'] = $get_zs+$get_zd;//收到礼物钻石价值

            $trends_info = M('trends')->where(['uid' => $auid])->order('create_time desc')->find();

            if($trends_info){
                $info['id'] = $trends_info['id'];
                $info['content'] = $trends_info['content'];
                $info['imgs'] = get_pictrues($trends_info['imgs']);
            }else{
                $info['id'] = 0;
                $info['content'] = '';
                $info['imgs'] = [];
            }

            $info['is_concern'] = is_concern($uid,$auid);

            $info['rank'] = exp_rank($info['exp']);
            $gz_info = gz_rank($auid);
            $info['gz_img'] = $gz_info['img'];

            unset($info['exp']);

            if($info){
                return api_return(1,'获取数据成功',$info);
            }else{
                return api_return(2,'获取数据失败');
            }

        }
    }

    /**
     * 礼物
     * */
    public function gift(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $cate_list = M('giftcate')->field('id as single_id,name')->where(['status' => 1])->select();

            foreach($cate_list as $k => $v){
                $gift_list[$k] = M('gift')->field('id as single_id,cate_id,name,value,img,special_img')->where(['cate_id' => $v['single_id'],'status' => 1])->select()?M('gift')->field('id as single_id,cate_id,name,value,img,special_img')->where(['cate_id' => $v['single_id'],'status' => 1])->select():[];
                foreach($gift_list[$k] as $key => $val){
                    $gift_list[$k][$key]['img'] = get_img($val['img']);
                    $gift_list[$k][$key]['special_img'] = $val['special_img']?$val['special_img']:'';
                    /*if($val['special_img'] == 0){
                        $gift_list[$k][$key]['special_img'] = '';
                    }else{
                        $gift_list[$k][$key]['special_img'] = get_img($val['special_img']);
                    }*/
                }
            }

            if($uid) $zs_blance = M('user')->where(['id' => $uid])->getField('zs_blance');
            $gift_num = explode(",",C('GIFT_NUM'));

            $data = [
                'cate_list' => $cate_list,
                'list' => $gift_list,
                'zs_num' => $zs_blance?$zs_blance:0,
                'gift_num' => $gift_num
            ];

            if($gift_list){
                return api_return(1,'获取数据成功',$data);
            }else{
                return api_return(1,'获取数据失败',[]);
            }
        }
    }

    /**
     * 赠送礼物
     * */
    public function send_gift(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];
            $name = $input['name'];
            $zs_num = $input['zs_num'];
            $num = $input['num'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($name)) return api_return(2,'请传入礼物名称');
            if(empty(is_numeric($zs_num))) return api_return(2,'请传入单个礼物所需钻石数');
            if(empty($num)) return api_return(2,'请传入赠送礼物数量');

            $send_profit = C('SEND_PROFIT');//赠送钻石时产生的贡献度
            $user_exp = C('USER_EXP');//用户经验值增长配置
            $zb_exp = C('ZB_EXP');//主播经验值增长配置

            $all_zs_num = $zs_num*$num;//送礼所需钻石

            $user_info = M('user')->field('zs_blance,zd_blance')->where(['id' => $uid])->find();

            if($all_zs_num > $user_info['zs_blance']+$user_info['zd_blance']){
                $data = [
                    'cue' => '',
                    'zs_num' => '',
                    'rank' => '',
                ];
                return api_return(2,'您的账户钻石和钻豆数量不足',$data);
            }else{
                $user_exp = $all_zs_num*$user_exp;//用户赠送礼物获得的经验值
                $zb_exp = $all_zs_num*$zb_exp;//主播收到礼物获得的经验值

                if($user_info['zs_blance'] >= $all_zs_num){
                    //钻石赠送
                    $type = 1;
                    $profit = $all_zs_num*$send_profit;//赠送礼物钻石价值产生的贡献度
                    M('user')->where(['id' => $uid])->setDec('zs_blance',$all_zs_num);
                    M('user')->where(['id' => $uid])->setInc('exp',$user_exp);//用户经验值提升
                    M('user')->where(['id' => $auid])->setInc('exp',$zb_exp);//主播经验值提升
                }elseif($user_info['zs_blance'] < $all_zs_num && $user_info['zd_blance'] >= $all_zs_num){
                    //钻豆赠送
                    $type = 2;
                    M('user')->where(['id' => $uid])->setDec('zd_blance',$all_zs_num);
                    M('user')->where(['id' => $uid])->setInc('exp',$user_exp);//用户经验值提升
                    M('user')->where(['id' => $auid])->setInc('exp',$zb_exp);//主播经验值提升
                }elseif($user_info['zs_blance'] < $all_zs_num && $user_info['zd_blance'] < $all_zs_num){
                    //混合赠送
                    $type = 3;
                    $profit = $user_info['zs_blance']*$send_profit;//赠送礼物钻石价值产生的贡献度
                    M('user')->where(['id' => $uid])->setField(['zs_blance' => 0]);
                    M('user')->where(['id' => $uid])->setDec('zd_blance', $all_zs_num-$user_info['zs_blance']);
                    M('user')->where(['id' => $uid])->setInc('exp',$user_exp);//用户经验值提升
                    M('user')->where(['id' => $auid])->setInc('exp',$zb_exp);//主播经验值提升
                }

                if($profit){
                    M('user')->where(['id' => $uid])->setInc('profit',$profit);//用户贡献度提升
                    M('user')->where(['id' => $auid])->setInc('profit',$profit);//主播贡献度提升
                }
                $data = [
                    'uid' => $uid,
                    'auid' => $auid,
                    'name' => $name,
                    'num' => $num,
                    'zs_num' => $zs_num,
                    'type' => $type,
                    'create_time' => time(),
                    'profit' => $profit
                ];

                M('record')->add(['uid' => $uid,'zs_num' => $zs_num,'desc' => '送礼','create_time' => time()]);

                $res = M('send_gift')->add($data);

                $gift_userinfo = M('user')->field('zs_blance,exp')->where(['id' => $uid])->find();

                $one_info = M('anchor')->field('is_one,blance')->where(['auid' => $auid])->find();

                if($one_info['is_one'] == 1){
                    //一对一直播中
                    $one_zs_blance = M('user')->where(['id' => $uid])->getField('zs_blance');//赠送礼物之后的剩余钻石数
                    if($one_zs_blance <= $one_info['blance']){
                        $cue = 1;
                    }else{
                        $cue = 0;
                    }
                }else{
                    $cue = 0;
                }

                $data = [
                    'cue' => $cue,
                    'zs_num' => $gift_userinfo['zs_blance'],
                    'rank' => exp_rank($gift_userinfo['exp']),
                ];

                if($res){
                    $is_send = M('gift')->where(['name' => $name])->getField('is_send');
                    if($is_send == 1){
                        //发送广播大群消息
                        $u_name = M('user')->where(['id' => $uid])->getField('nickname');//用户名
                        $a_name = M('user')->where(['id' => $auid])->getField('nickname');//主播名
                        $text = $u_name.'在'.$a_name.'的直播间送出'.$name;
                        send_groud_msg($text);
                    }

                    $map['uid'] = array('eq',$auid);
                    $map['buid'] = array('eq',$auid);
                    $map['_logic'] = 'or';
                    $where['_complex'] = $map;
                    $where['status']  = array('eq',1);
                    $is_pk = M('pk')->where($where)->count();//0:未pk；1:pk中
                    if($is_pk == 1){
//                        file_put_contents(RUNTIME_PATH.'is_pk.txt',M()->getLastSql());
                        //pk是单独计算礼物数（钻石）
                        $pk_map['uid'] = array('eq',$auid);
                        $pk_map['buid'] = array('eq',$auid);
                        $pk_map['_logic'] = 'or';
                        $where['_complex'] = $pk_map;
                        $where['status']  = array('eq',1);
                        $pk_info = M('pk')->field('uid,buid')->where($where)->find();
//                        file_put_contents(RUNTIME_PATH.'gift_log.txt',M()->getLastSql());
                        if($pk_info['uid'] == $auid){
                            //当前主播为pk发起者
                            M('pk')->where(['uid' => $auid])->setInc('pknum',$all_zs_num);
                        }else{
                            //当前主播为pk接受者
                            $buid = $pk_info['uid'];//对方主播id
                            M('pk')->where(['uid' => $buid])->setInc('bpknum',$all_zs_num);
                        }
                    }
                    return api_return(1,'赠送礼物成功',$data);
                }else{
                    $data = [
                        'cue' => '',
                        'zs_num' => '',
                        'rank' => '',
                    ];
                    return api_return(2,'赠送礼物失败',$data);
                }
            }
        }
    }
    /*****************用户端直播间*******************/


    /*****************主播端**********************/

    /**
     * 接受pk
     * */
    public function do_pk(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];
            $type = $input['type'];//1：接受，2：拒绝

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入主播id');
            if(empty($auid)) return api_return(2,'请传入对方主播id');

            $count = M('pk')->where(['uid' => $auid,'buid' => $uid,'status' => 0])->count();
            $pk_time = M('pk')->where(['uid' => $auid,'buid' => $uid,'status' => 0])->getField('pk_time');

            if($count){
                if($type == 1){
                    $res = M('pk')->where(['uid' => $auid,'buid' => $uid,'status' => 0])->save(['status' => 1]);
                    $data = [
                        'status' => 1,
                        'pk_time' => $pk_time*60*1000
                    ];
                }else{
                    $res = M('pk')->where(['uid' => $auid,'buid' => $uid,'status' => 0])->save(['status' => 2,'create_time' => time()]);
                    $data = [
                        'status' => 2,
                        'pk_time' => $pk_time*60*1000
                    ];
                }
            }
            if($res){
                return api_return(1,'操作成功',$data);
            }else{
                return api_return(2,'操作失败',['status' => '', 'pk_time' => '']);
            }
        }
    }

    /**
     * pk列表
     * */
    public function pk_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];
            $n = $input['n'];
            $num = $input['num'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $where['status'] = array('neq',2);
            $ids = M('pk')->field('buid')->where(['uid' => $auid,'status' => 1])->select();//该主播已向哪些主播发起pk请求

            $offset = ($n-1)*$num;
            $map['a.auid'] = array('neq',$auid);
            $list = M('anchor')->alias('a')
                ->join('zb_user u ON a.auid = u.id')
                ->field('a.auid,a.number,u.nickname')
                ->where(['a.is_show' => 2])
                ->where($map)
                ->limit($offset,$num)
                ->select();

            if($list){
                foreach($list as $k => &$v){
                    foreach($ids as $key => $val){
                        if($val['buid'] == $v['auid']){
                            array_splice($list,$k,1);
                        }
                    }
                    $v['avatar_img'] = get_avatar($v['auid']);
                }
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }

        }
    }

    /**
     * 发起pk
     * */
    public function check_pk(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $auid = $input['auid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入主播id');//发起者
            if(empty($auid)) return api_return(2,'请传入对方主播id');

            $info = M('pk_set')->find();

            $time = date('H:i',time());
            if($time < $info['start_time'] || $time > $info['end_time']) return api_return(2,'发起pk失败，pk通道开启时间：'.$info['start_time'].'~'.$info['end_time']);

            $pk_info = M('pk')->where(['uid' => $auid,'buid' => $uid,'status' => 0])->find();
            if(time()-$pk_info['create_time'] < 10){
                return api_return(2,'发起pk操作过于频繁，请稍后再试');
            }else{
                //距离上次发起pk超过10秒，可以再次发起，之前的pk记录改为拒绝pk状态
                M('pk')->where(['uid' => $auid,'buid' => $uid,'status' => 0])->setField('status',2);
            }
            //if(count($pk_info) > 0) return api_return(2,'请勿重复发起pk请求');

            $add_data = [
                'uid' => $uid,
                'buid' => $auid,
                'pk_time' => $info['pk_time'],
                'create_time' => time()
            ];

            $res = M('pk')->add($add_data);
            if($res){
                return api_return(1,'pk请求发送成功',$info['pk_time']*60*1000);
            }else{
                return api_return(2,'pk请求发送失败');
            }
        }
    }

    /**
     * 检测pk，客户端每隔多久调用一次
     * 1：检测pk是否已经结束
     * 2：返回双方钻石和比例计算
     * */
    public function examine_pk(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'主播id不能为空');


            $map['uid'] = array('eq',$auid);
            $map['buid'] = array('eq',$auid);
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
            $where['status']  = array('eq',1);
            $pk_info = M('pk')->field('uid,buid,pknum,bpknum,create_time,pk_time')->where($where)->find();

            if($pk_info['uid'] == $auid){
                //当前主播为pk发起者
                $pknum = $pk_info['pknum'];
                $bpknum = $pk_info['bpknum'];
                $ratio = intval(($pknum/($pknum+$bpknum))*100);
                $b_ratio = intval(100-$ratio);
            }else{
                //当前主播为pk接受者
                $pknum = $pk_info['bpknum'];
                $bpknum = $pk_info['pknum'];
                $ratio = intval(($pknum/($pknum+$bpknum))*100);
                $b_ratio = intval(100-$ratio);
            }
            $data = [
                'pknum' => $pknum,
                'bpknum' => $bpknum,
                'ratio' => $ratio,
                'b_ratio' => $b_ratio,
            ];
            if(empty($pknum) && empty($bpknum)){
                $data['ratio'] = 50;
                $data['b_ratio'] = 50;
            }

            $end_time = $pk_info['create_time']+$pk_info['pk_time']*60;//该pk直播结束的时间戳
            if(time() >= $end_time){
                $res = M('pk')->where($where)->setField('status',2);
                if($res){
                    return api_return(1,'该pk直播已结束',$data);
                }else{
                    return api_return(2,'结束pk直播异常');
                }
            }else{
                return api_return(1,'该pk直播进行中',$data);
            }

        }
    }

    public function end_pk(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'主播id不能为空');

            $map['uid'] = array('eq',$auid);
            $map['buid'] = array('eq',$auid);
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
            $where['status']  = array('eq',1);
            $res = M('pk')->where($where)->setField('status',2);
            if($res){
                return api_return(1,'结束pk成功');
            }else{
                return api_return(2,'结束pk失败');
            }
        }
    }

    /**
     * 主播端直播间数据显示
     * */
    public function anchors_side(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $zb_sh = zb_sh($auid);//主播守护人数
            $music_count = music_count($auid);

            $anchor_info = zb_user_info($auid);

            $data = [
                'avatar_img' => $anchor_info['avatar_img'],
                'nickname' => $anchor_info['nickname'],
                'sh' => $zb_sh,
                'music_count' => $music_count
            ];

            return api_return(1,'获取数据成功',$data);
        }
    }

    /**
     * 主播端pk直播间数据显示
     * */
    public function anchors_side_pk(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $map['uid'] = array('eq',$auid);
            $map['buid'] = array('eq',$auid);
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
            $where['status']  = array('eq',1);
            $pk_info = M('pk')->field('uid,buid,pknum,bpknum')->where($where)->find();

            if($pk_info['uid'] == $auid){
                //当前主播为pk发起者
                $buid = $pk_info['buid'];//对方主播id
                $buid_info = zb_user_info($buid);
                $pknum = $pk_info['pknum'];
                $bpknum = $pk_info['bpknum'];
            }else{
                //当前主播为pk接受者
                $buid = $pk_info['uid'];//对方主播id
                $buid_info = zb_user_info($buid);
                $pknum = $pk_info['bpknum'];
                $bpknum = $pk_info['pknum'];
            }

            $zb_sh = zb_sh($auid);//主播守护人数
            $music_count = music_count($auid);

            $anchor_info = zb_user_info($auid);

            $count = M('anchor')->where(['auid' => $auid])->getField('count');//在线观看人数
            $data = [
                'avatar_img' => $anchor_info['avatar_img'],
                'nickname' => $anchor_info['nickname'],
                'sh' => $zb_sh,
                'music_count' => $music_count,
                'count' => $count?$count:0,
                'pknum' => $pknum,
                'b_avatar_img' => $buid_info['avatar_img'],
                'b_nickname' => $buid_info['nickname'],
                'bpknum' => $bpknum
            ];

            return api_return(1,'获取数据成功',$data);
        }
    }

    /**
     * 音乐库
     * */
    public function all_music_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;
            $title = $input['title'];//搜索歌曲名

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $offset =  ($n-1)*$num;

            if($auid){
                $list = M('zbmusic')->alias('z')
                    ->join('zb_music m ON z.music_id = m.id')
                    ->field('z.music_id,m.title,z.music_type,z.zs_num,yc_url,bz_url')
                    ->where(['z.auid' => $auid])
                    ->limit($offset,$num)
                    ->select();//主播歌曲列表
                foreach($list as $k => $v){
                    if(!empty($v['yc_url']) && empty($v['bz_url'])){
                        $list[$k]['edit_music_type'] = 1;
                    }elseif(empty($v['yc_url']) && !empty($v['bz_url'])){
                        $list[$k]['edit_music_type'] = 2;
                    }else{
                        $list[$k]['edit_music_type'] = 3;
                    }
                    unset($list[$k]['yc_url']);
                    unset($list[$k]['bz_url']);
                }
            }else{
                if(!empty($title)){
                    $map['title'] = array('like','%'.$title.'%');
                }
                $list = M('music')->where($map)->limit($offset,$num)->select();
            }

            foreach($list as $k => $v){
                if(!$auid){
                    if(!empty($v['yc_url']) && empty($v['bz_url'])){
                        $list[$k]['music_type'] = 1;
                    }elseif(empty($v['yc_url']) && !empty($v['bz_url'])){
                        $list[$k]['music_type'] = 2;
                    }else{
                        $list[$k]['music_type'] = 3;
                    }
                }
                unset($list[$k]['yc_url']);
                unset($list[$k]['bz_url']);
                unset($list[$k]['create_time']);
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 音乐库添加歌曲（一：歌曲数据查询）
     * */
    public function music_info(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];//歌曲id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'请传入歌曲id');

            $info = M('music')->where(['id' => $id])->find();

            if($info){
                if(!empty($info['yc_url']) && empty($info['bz_url'])){
                    $info['music_type'] = 1;
                }elseif(empty($info['yc_url']) && !empty($info['bz_url'])){
                    $info['music_type'] = 2;
                }else{
                    $info['music_type'] = 3;
                }
                return api_return(1,'获取数据成功',$info);
            }else{
                return api_return(2,'获取数据失败');
            }
        }
    }

    /**
     * 音乐库添加歌曲（二：数据入库）
     * */
    public function music_do(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];//歌曲id
            $auid = $input['auid'];//主播id
            $music_type = $input['music_type'];//歌曲类型
            $zs_num = $input['zs_num'];//钻石数
            $type = $input['type'];//1：添加；2：修改

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'请传入歌曲id');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($music_type)) return api_return(2,'请传入歌曲类型');
            if(empty($zs_num)) return api_return(2,'请传入钻石数');
            if(empty($type)) return api_return(2,'请传入操作类型');

            if($type == 1){
                $count = M('zbmusic')->where(['auid' => $auid,'music_id' => $id])->count();
                if($count) return api_return(2,'您已添加该歌曲，请勿重复添加');

                $data = [
                    'music_id' => $id,
                    'auid' => $auid,
                    'music_type' => $music_type,
                    'zs_num' => $zs_num
                ];
                $res = M('zbmusic')->add($data);
            }else{

                $data = [
                    'music_type' => $music_type,
                    'zs_num' => $zs_num
                ];
                $res = M('zbmusic')->where(['music_id' => $id, 'auid' => $auid])->save($data);
            }

            if($res){
                return api_return(1,'操作成功');
            }else{
                return api_return(2,'操作失败');
            }
        }
    }

    /**
     * 已选歌曲
     * */
    public function my_check_music(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $list = M('zbmusic')->alias('z')
                ->field('z.music_id,z.music_type,z.zs_num,m.title')
                ->join('zb_music m ON z.music_id = m.id')
                ->where(['z.auid' => $auid])
                ->select();

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'获取数据失败',[]);
            }
        }
    }

    /**
     * 删除歌曲
     * */
    public function del_music(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $music_id = $input['music_id'];//歌曲id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($music_id)) return api_return(2,'请传入歌曲id');

            $res = M('zbmusic')->where(['auid' => $auid, 'music_id' => $music_id])->delete();
            if($res){
                return api_return(1,'删除成功');
            }else{
                return api_return(2,'删除失败');
            }
        }
    }

    /**
     * 修改（已选歌曲）
     * */
    public function show_music(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];//主播id
            $music_id = $input['music_id'];//歌曲id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($music_id)) return api_return(2,'请传入歌曲id');

            $info = M('zbmusic')->alias('z')
                ->field('z.music_id,z.music_type,z.zs_num,m.title')
                ->join('zb_music m ON z.music_id = m.id')
                ->where(['z.auid' => $auid, 'z.music_id' => $music_id])
                ->find();

            if($info){
                return api_return(1,'获取数据成功',$info);
            }else{
                return api_return(2,'获取数据失败',[]);
            }
        }
    }

    /**
     * （已点/已唱）歌曲
     * */
    public function music_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;
            $type = $input['type'];//1：已点；2：已唱

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($type)) return api_return(2,'请传入类型id');

            if($type == 1){
                //已点
                $is_sing = 0;
                $order = 'y.create_time asc';
            }else{
                //已唱
                $is_sing = 1;
                $order = 'y.create_time desc';
            }

            $offset = ($n-1)*$num;
            $list = M('ydmusic')->alias('y')
                ->field('y.id,y.music_type,u.id uid,u.nickname,m.title,m.yc_url,m.bz_url,u.exp')
                ->join('zb_user u ON y.uid = u.id')
                ->join('zb_music m ON y.music_id = m.id')
                ->where(['y.auid' => $auid, 'y.is_sing' => $is_sing])
                ->order($order)
                ->limit($offset,$num)
                ->select();

            foreach($list as $k => $v){
                $list[$k]['single_id'] = $v['id'];
                $list[$k]['avatar_img'] = get_avatar($v['id']);
                $list[$k]['rank'] = exp_rank($v['exp']);
                $gz_info = gz_rank($v['uid']);
                $list[$k]['gz_img'] = $gz_info['img'];
                $list[$k]['yc_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$v['yc_url'];
                $list[$k]['bz_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$v['bz_url'];
                unset($list[$k]['id']);
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 开唱
     * */
    public function sing(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];
            $auid = $input['auid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'请传入歌曲id');
            if(empty($auid)) return api_return(2,'请传入主播id');


//            M('zbmusic')->where(['auid' => $auid])->setField(['singing' => 0]);

//            M('zbmusic')->where(['auid' => $auid,'music_id' => $id])->setField(['singing' => 1]);
            $res = M('ydmusic')->where(['id' => $id, 'auid' => $auid])->save(['is_sing' => 1,'sing_time' => time()]);
            if($res){
                return api_return(1,'操作成功');
            }else{
                return api_return(2,'操作失败');
            }
        }
    }

    /**
     * （设置/取消）管理
     * */
    public function do_manage(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $vuid = $input['vuid'];
            $auid = $input['auid'];
            $type = $input['type'];//1：设置管理员；2：取消管理员

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($vuid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');
            if(empty($type)) return api_return(2,'请传入类型id');

            $res = M('viewer')->where(['vuid' => $vuid, 'auid' => $auid])->setField(['is_manager' => $type]);

            if($res){
                if($type == 1){
                    return api_return(1,'设置管理员成功');
                }else{
                    return api_return(1,'取消管理员成功');
                }
            }else{
                if($type == 1){
                    return api_return(2,'设置管理员失败');
                }else{
                    return api_return(2,'取消管理员失败');
                }
            }
        }
    }

    /**
     * 连麦列表
     * */
    public function lianmai_list(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $auid = $input['auid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $offset = ($n-1)*$num;
            $list = M('lianmai')->alias('l')
                ->field('l.id,u.id uid,u.nickname')
                ->join('zb_user u ON l.uid = u.id')
                ->where(['l.auid' => $auid, 'status' => 0])
                ->limit($offset,$num)
                ->order('l.create_time asc')
                ->select();

            foreach($list as $k => $v){
                $list[$k]['avatar_img'] = get_avatar($v['uid']);
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /*****************主播端**********************/

    /**
     * 我的消息（未读消息数量得显示）
     * */
    public function my_mess(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $data['sys_mess_count'] = mess_count($uid);
            $data['zb_mess'] = count(zb_concern_mess_count($uid));

            return api_return(1,'成功',$data);
        }
    }


    /**
     * 查看系统消息详情时执行
     * */
    public function sys_mess(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $id = $input['id'];//消息id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(empty($id)) return api_return(2,'请传入详情id');

            M('official')->add(['uid' => $uid,'mid' => $id]);

            return api_return(1,'成功');
        }
    }


    /**
     * 我的消息 => 新增关注
     * 点击新增关注时执行
     * */
    public function zb_mess(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $mess_list = zb_concern_mess_count($uid);
            foreach($mess_list as $k => $v){
                M('official')->add(['uid' => $uid,'mid' => $v['id']]);
            }

            return api_return(1,'成功');
        }
    }

    /**
     * 个人中心 => 粉丝
     * 点击粉丝时执行
     * */
    public function user_mess(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $mess_list = user_concern_mess_count($uid);
            foreach($mess_list as $k => $v){
                M('official')->add(['uid' => $uid,'mid' => $v['id']]);
            }

            return api_return(1,'成功');
        }
    }

    /**
     * 清空最近观看记录
     * */
    public function clear_lately(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $res = M('lately')->where(['uid' => $uid])->setField(['is_delete' => 1]);
            if($res){
                return api_return(1,'操作成功');
            }else{
                return api_return(2,'操作失败');
            }
        }
    }

    /**
     * 搜索
     * */
    public function search_user(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $content = $input['content'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
//            if(empty($content)) return api_return(2,'搜索内容不能为空');

            if($content){
                $map['nickname'] = array('like','%'.$content.'%');
                $map['number'] = array('eq',$content);
                $map['_logic'] = 'or';
            }

            $offset = ($n-1)*$num;
            $list = M('user')->field('id,nickname,number,funs_num,exp')->where($map)->limit($offset,$num)->select();

            foreach($list as $k => $v){
                $list[$k]['avatar_img'] = get_avatar($v['id']);
                $list[$k]['rank'] = exp_rank($v['exp']);
            }

            if($list){
                return api_return(1,'获取数据成功',$list);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 当前贵族信息
     * */
    public function now_gz_info(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $info = gz_rank($uid);

            if($info){
                return api_return(1,'获取数据成功',$info);
            }else{
                return api_return(1,'暂无更多数据',[]);
            }
        }
    }

    /**
     * 预开播
     * */
    public function ready_open_show(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            $is_anchor = M('user')->where(['id' => $uid])->getField('is_anchor');
            if(!$is_anchor) return api_return(2,'您还不是主播');

            $exp = M('user')->where(['uid' => $uid])->getField('exp');
            if(exp_rank($exp) < C('ZB_RANK')) return api_return(2,'等级大于'.C('ZB_RANK').'级才可以开直播');

            $count = M('anchor')->where(['auid' => $uid])->count();

            //获取房间号
            $number = M('user')->where(['id' => $uid])->getField('number');

            //创建时间
            $create_time = time();
            //过期时间
            $expire_time = time()+24*60*60;
            //生成推流地址
            $push_url = getPushUrl($number,date('Y-m-d H:i:s',$expire_time));
            //获取播放地址
            $play_url = flv_getPlayUrl($number);
            //获取拉流地址
            $lm_play_url = lm_getPlayUrl($number,date('Y-m-d H:i:s',$expire_time+1));

            $data = [
                'number' => $number,
                'push_url' => $push_url,
                'play_url' => $play_url,
                'lm_play_url' => $lm_play_url,
                'create_time' => $create_time,
                'expire_time' => $expire_time,
                'is_show' => 1
            ];

            if($count > 0){
                //之前开播过，修改数据
                $res = M('anchor')->where(['auid' => $uid])->save($data);
            }else{
                //第一次开播，添加数据
                $data['auid'] = $uid;
                $res = M('anchor')->add($data);
            }

            $roomID = 'room_'.rand(10000000,99999999);

            $data = [
                'push_url' => $push_url,
                'roomID' => $roomID
            ];

            if($res){
                M('anchor')->where(['auid' => $uid])->setField('temp_room_id',$roomID);

                return api_return(1,'成功',$data);
            }else{
                return api_return(2,'失败');
            }
        }
    }

    /**
     * 开播
     * */
    public function open_show(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $lng = $input['lng']?$input['lng']:0;//经度
            $lat = $input['lat']?$input['lat']:0;//纬度

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $res = M('anchor')->where(['auid' => $uid])->setField(['is_show' => 2]);
            if($res){
                $Groupid = C('GROUPID')?C('GROUPID'):'';
                M('user')->where(['id' => $uid])->setField(['lng' => $lng,'lat' => $lat]);
                return api_return(1,'开播成功',$Groupid);
            }else{
                return api_return(2,'开播失败');
            }
        }
    }

    /**
     * 用户进入直播间时执行
     * */
    public function add_viewer(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $vuid = $input['vuid']?$input['vuid']:0;//用户id
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $is_out = M('viewer')->where(['vuid' => $vuid,'auid' => $auid,'is_out' => 1])->count();
            if($is_out) return api_return(2,'您已被踢出房间，该主播下次开播才可进入房间');

            $is_one = M('anchor')->where(['auid' => $auid])->getField('is_one');

            $data = [
                'is_manager' => intval(0),
                'look_count' => intval(0),
                'rank' => intval(0),
                'Groupid' => '',
                'is_pk' => ''
            ];

            if($is_one == 1){
                //一对一直播中
                $count = M('viewer')->where(['auid' => $auid,'is_room' => 1])->count();
                if($count > 0){
                    return api_return(2,'该主播一对一直播中，直播间已满员',$data);
                }else{
                    $blance = M('anchor')->where(['auid' => $auid])->getField('blance');//一对一每分钟钻石价格
                    $zs_blance = M('user')->where(['id' => $vuid])->getField('zs_blance');//用户钻石余额

                    if($zs_blance < $blance){
                        return api_return(2,'您的账户钻石余额不足，加入一对一直播间失败');
                    }
                }

            }

            if($vuid){
                $count = M('viewer')->where(['vuid' => $vuid,'auid' => $auid])->count();

                if($count){
                    //setField
                    $res = M('viewer')->where(['vuid' => $vuid,'auid' => $auid])->save(['is_room' => 1,'create_time' => time()]);
                }else{
                    //add
                    $data = [
                        'auid' => $auid,
                        'vuid' => $vuid,
                        'is_room' => 1,
                        'is_manager' => 2,
                        'create_time' => time()
                    ];

                    $res = M('viewer')->add($data);
                }

                if($res){
                    $look_count = M('viewer')->where(['auid' => $auid, 'is_room' => 1])->count();
                    $is_manager = M('viewer')->where(['vuid' => $vuid,'auid' => $auid])->getField('is_manager');
                    $exp = M('user')->where(['id' => $vuid])->getField('exp');
                    $title = singing($auid);//正在唱的歌曲
                    $Groupid = C('GROUPID')?C('GROUPID'):'';

                    //查询该主播是否在pk中
                    $map['uid'] = array('eq',$auid);
                    $map['buid'] = array('eq',$auid);
                    $map['_logic'] = 'or';
                    $where['_complex'] = $map;
                    $where['status']  = array('eq',1);
                    $pk_count = M('pk')->where($where)->count();
                    if($pk_count > 0){
                        $is_pk = 1;
                    }else{
                        $is_pk = 0;
                    }

                    $data = [
                        'is_manager' => intval($is_manager),
                        'look_count' => intval($look_count),
                        'rank' => intval(exp_rank($exp)),
                        'Groupid' => $Groupid,
                        'is_pk' => $is_pk
                    ];

                    M('anchor')->where(['auid' => $auid, 'is_show' => 2])->setInc('count');//在线人数+1

                    $lately_data = [
                        'uid' => $vuid,
                        'cuid' => $auid,
                        'create_time' => time(),
                        'is_delete' => 0
                    ];

                    $lately_count = M('lately')->where(['uid' => $vuid,'cuid' => $auid])->count();
                    if($lately_count>0){
                        //多次看该主播，修改数据
                        M('lately')->where(['uid' => $vuid,'cuid' => $auid])->save(['create_time' => time(),'is_delete' => 0]);
                    }else{
                        //第一次看该主播，添加数据
                        M('lately')->add($lately_data);
                    }

                    return api_return(1,'加入直播间成功',$data);
                }else{
                    return api_return(2,'加入直播间失败',$data);
                }
            }else{
                $look_count = M('viewer')->where(['auid' => $auid, 'is_room' => 1])->count();
                $Groupid = C('GROUPID')?C('GROUPID'):'';

                //查询该主播是否在pk中
                $map['uid'] = array('eq',$auid);
                $map['buid'] = array('eq',$auid);
                $map['_logic'] = 'or';
                $where['_complex'] = $map;
                $where['status']  = array('eq',1);
                $pk_count = M('pk')->where($where)->count();
                if($pk_count > 0){
                    $is_pk = 1;
                }else{
                    $is_pk = 0;
                }
                $data = [
                    'is_manager' => intval(0),
                    'look_count' => intval($look_count),
                    'rank' => intval(0),
                    'Groupid' => $Groupid,
                    'is_pk' => $is_pk
                ];
                return api_return(1,'未登录状态',$data);
            }
        }
    }

    /**
     * 匿名登录
     * */
    public function fake_login(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $fake_number = rand(1000000,9999999);
            $usersig = get_UserSig($fake_number);

            $roomservicesign = array("sdkAppID" => C('YUN_SDKAPPID'), "accountType" => C('ACCOUNT_TYPE'), "userID" => $fake_number, "userSig" => $usersig);

            return api_return(1,'匿名登录成功',$roomservicesign);
        }
    }

    /**
     * 一对一直播消费钻石及监控钻石数
     * */
    public function one_spend(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $vuid = $input['vuid'];//用户id
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($vuid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $blance = M('anchor')->where(['auid' => $auid])->getField('blance');//一对一每分钟钻石价格

            $res = M('user')->where(['id' => $vuid])->setDec('zs_blance',$blance);//扣除用户钻石数
            if($res){
                $user_exp = C('USER_EXP');//经验值提升比例
                $up_exp = $blance*$user_exp;
                M('user')->where(['id' => $vuid])->setInc('exp',$up_exp);
                $surplus_zs = M('user')->where(['id' => $vuid])->getField('zs_blance');//用户剩余钻石数
                if($surplus_zs <= $blance){
                    $data['cue'] = 1;
                }else{
                    $data['cue'] = 0;
                }

                $data['surplus_zs'] = $surplus_zs;
            }
            return api_return(1,'一对一直播中',$data);
        }
    }

    /**
     * 用户退出直播间时执行
     * */
    public function exit_viewer(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $vuid = $input['vuid'];//用户id
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($auid)) return api_return(2,'请传入主播id');

            if($vuid){
                $res = M('viewer')->where(['vuid' => $vuid, 'auid' => $auid])->setField('is_room',0);
                if($res){
                    M('anchor')->where(['auid' => $auid])->setDec('count');//在线观看人数-1
                    return api_return(1,'退出直播间成功');
                }else{
                    return api_return(2,'退出直播间失败');
                }
            }else{
                return api_return(1,'用户未登录情况下无需执行该接口');
            }
        }
    }

    /**
     * 踢人
     * */
    public function shot_off(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $vuid = $input['vuid'];//用户id
            $auid = $input['auid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($vuid)) return api_return(2,'请传入用户id');
            if(empty($auid)) return api_return(2,'请传入主播id');

            $data = [
                'is_out' => 1,
                'is_room' => 0
            ];
            $res = M('viewer')->where(['vuid' => $vuid, 'auid' => $auid])->save($data);
            if($res){
                return api_return(1,'踢出成功');
            }else{
                return api_return(2,'踢出失败');
            }
        }
    }

    /**
     * 下播
     * */
    public function close_show(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];//主播id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');

            $res = M('anchor')->where(['auid' => $uid])->save(['is_show' => 0,'temp_room_id' => '','count' => 0,'is_one' => 0]);

            $data = [
                'is_room' => 0,
                'is_out' => 0
            ];

            M('ydmusic')->where(['auid' => $uid])->delete();
            M('viewer')->where(['auid' => $uid])->save($data);

            if($res){
                return api_return(1,'下播成功');
            }else{
                return api_return(2,'下播失败');
            }
        }
    }

    /**
     * 省市区
     */
    public function address_link(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $db = M('district');
            $one = $db->field('id,name province')->where(['level' => 1])->select();

            foreach($one as $k => $v){
                $city = $db->field('name')->where(['upid' => $v['id']])->select();
                foreach($city as $vc){
                    $two[$k][] = $vc['name'];
                }
            }

            foreach($one as $k => $v){
                $city = $db->field('id,name')->where(['upid' => $v['id']])->select();
                foreach($city as $key => $val){
                    $area = $db->field('name')->where(['upid' => $val['id']])->select();
                    foreach($area as $kk => $vv){
                        $three[$k][$key][] = $vv['name'];
                    }
                }
            }

            foreach($one as $k => $v){
                $city = $db->field('id as cid,name')->where(['upid' => $v['id']])->select();
                $one[$k]['city'] = $city;
                foreach($city as $key => $val){
                    $one[$k]['city'][$key]['area'] = $db->field('id as aid,name')->where(['upid' => $val['cid']])->select();
                }
            }

            $data = [
                'one' => $one,
                'two' => $two,
                'three' => $three
            ];

            if($data){
                return api_return(1,'获取数据成功', $data);
            }else{
                return api_return(2,'无数据');
            }
        }
    }

    /**
     * 生成推流url
     *
     * */
    public function getPushUrl(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入用户id');
            if(M('user')->where(['id' => $uid])->getField('is_anchor') == 0) return api_return(2,'您还不是主播');

            $info = M('user')->field('number,play_expire_time')->where(['id' => $uid])->find();

            if($info['play_expire_time'] > time()){
                //未过期，恢复上次推流地址
                $play_expire_time = $info['play_expire_time'];
            }else{
                //过期，重新生成推流地址
                $play_expire_time = time()+24*3600;
                M('user')->where(['id' => $uid])->save(['play_expire_time' => $play_expire_time, 'is_show' => 1]);
            }

            $time = date('Y-m-d H:i:s',$play_expire_time);
            $url = getPushUrl($info['number'],$time);


            return api_return(1,'生成推流url成功',$url);
        }
    }

    /**
     * 获取播放url
     * */
    public function getPlayUrl(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'请传入主播id');

            $room_id = M('user')->where(['id' => $uid])->getField('number');
            $url_arr = getPlayUrl($room_id);

            if($url_arr){
                return api_return(1,'获取播放url成功',$url_arr);
            }else{
                return api_return(2,'获取播放url失败',[]);
            }
        }
    }

    /**
     * 云通信
     * 生成userSig
     * */
    public function test4(){
        vendor('userSig.WebRTCSigApi');
        /* demo */
        try{
            $sdkappid = C('ZB_APPID');  //腾讯云云通信sdkappid
            $roomid = 123456;          //音视频房间号roomid
            $userid = "Dave";    //用户名userid


            $api = new \WebRTCSigApi();

            //设置在腾讯云申请的sdkappid
            $api->setSdkAppid($sdkappid);

            //读取私钥的内容
            //PS:不要把私钥文件暴露到外网直接下载了哦
            $private = file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'private_key');
            //设置私钥(签发usersig需要用到）
            $api->SetPrivateKey($private);

            //读取公钥的内容
            $public = file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'public_key');
            //设置公钥(校验userSig和privMapEncrypt需要用到，校验只是为了验证，实际业务中不需要校验）
            $api->SetPublicKey($public);


            //生成privMapEncrypt
            $privMapEncrypt = $api->genPrivMapEncrypt($userid, $roomid);

            //生成userSig
            $userSig = $api->genUserSig($userid);

            //校验
            $result = $api->verifyUserSig($userSig, $userid, $init_time, $expire_time, $error_msg);
            $result = $api->verifyPrivMapEncrypt($privMapEncrypt, $userid, $init_time, $expire_time, $userbuf, $error_msg);


            //打印结果
            $ret =  array(
                'privMapEncrypt' => $privMapEncrypt,
                'userSig' => $userSig
            );
            echo json_encode($ret);
            echo "\n";

        }catch(Exception $e){
            echo $e->getMessage();
        }
    }

    /**
     * 互动直播
     * 调用TLS api生成sig
     * 在控制台上下载的公私钥文件名分别为 private_key 和 public_key，分别对应下面的 ec_key.pem 和 public.pem。请在使用公私钥时注意区分。
     * */
    public function test5(){
        vendor('TLSSig.TLSSig');
        try{
            $api = new \TLSSigAPI();
            $api->SetAppid(1);
            $private = file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'ec_key.pem');
            $api->SetPrivateKey($private);
            $public = file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'public.pem');
            $api->SetPublicKey($public);
            $sig = $api->genSig('user1');
            $result = $api->verifySig($sig, 'user1', $init_time, $expire_time, $error_msg);
            var_dump($result);
            var_dump($init_time);
            var_dump($expire_time);
            var_dump($error_msg);

            $result = $api->verifySig($sig, 'user2', $init_time, $expire_time, $error_msg);
            var_dump($result);
            var_dump($init_time);
            var_dump($expire_time);
            var_dump($error_msg);
        }catch(Exception $e){
            echo $e->getMessage();
        }
    }

    public function test7(){
//        $room_id = M('user')->where(['id' => 1])->getField('number');
        $res = get_live_info('Get_LivePlayStat',1,10,'27240_88996655');
        echo $res;
    }
    public function test8(){
        $res = search_live_channe_list();
        dump(json_decode($res,true));
    }
    public function online_test(){
        $res = search_live_channe_list('Get_LiveStat');
        $info = json_decode($res,true);
        dump($info);exit;
        echo $info['output']['total_online'];
    }

    public function replace_channel($channel_id){
        str_replace(C('ZB_BIZID').'_','',$channel_id);
    }

    public function curl(){
        $skill_id = 1;
        header('content-type:text/html;charset=utf8');
        $res = '{"code":0,"message":"请求成功","rooms":[{"roomID":"room_1532516310337_53f5","roomInfo":"{\"title\":\"是你说\",\"frontcover\":\"\",\"location\":\"长沙市 银盆南路奥克斯中央公馆\"}","roomCreator":"wolf123456","mixedPlayURL":"https://27240.liveplay.myqcloud.com/live/27240_wolf123456.flv","audienceCount":null,"pushers":[{"userID":"wolf123456","userName":"wolf123456","userAvatar":"","accelerateURL":"rtmp://27240.liveplay.myqcloud.com/live/27240_wolf123456?bizid=27240&txSecret=b6a62ccfc143989a6dc264af6a49941b&txTime=5B619256"}]}]}';

//        $arr = json_decode($res,true);
        /*$rooms = $arr['rooms'];

        foreach($rooms as $k => $v){

            $skill_id = M('user')->where(['number' => $v['roomCreator']])->getField('skill_id');
            $rooms[$k]['skill_id'] = $skill_id?$skill_id:0;
        }*/
        echo $res;
    }

    public function live_test(){
        $live_list = search_live_channe_list();
        $live_list = json_decode($live_list,true);

        $live_list = $live_list['output']['channel_list'];

        foreach($live_list as $k => $v){
            $channel_id = str_replace(C('ZB_BIZID').'_','',$v['channel_id']);
        }

        dump($live_list);
    }

    public function zb_list_test(){

        $userid = I('post.userid');
        $token = I('post.token');

        $header=array(
            "Accept: application/json",
            "Content-Type: application/json;charset=utf-8",
        );

        $url = 'https://room.qcloud.com/weapp/live_room/get_room_list?userID='.$userid.'&token='.$token;

        $param = [
            'cnt' => 1000,
            'index' => 0
        ];

        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名（为0也可以，就是连域名存在与否都不验证了）

        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($param));

        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        echo $data;
    }

}
